spring boot 启动时运行代码(2)ApplicationListener

项目概览:

StepExecutor:

@Component
@Slf4j
public class StepExecutor implements Runnable {
    @Autowired
    private HelloService helloService;
    
    @Override
    public void run() {
        log.info("1111111111111111,helloService={}",helloService);
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        helloService.hello();
        log.info("22222222222222222");
    }
}

ApplicationStartup

public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext ac = event.getApplicationContext();
        StepExecutor stepExecutor = ac.getBean(StepExecutor.class);
        Thread thread = new Thread(stepExecutor);
        thread.start();
    }
}

Application

@SpringBootApplication
@ComponentScan(basePackages="com.ebc")
@EnableAutoConfiguration //必须加该注解,否则报:缺少ServletWebServerFactory bean
@Slf4j
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.addListeners(new ApplicationStartup());
        app.run(args);
        log.info("PortalApplication is success!");
    }
}

HelloService

@Service
public class HelloService {
    public void hello() {
       Console.log("xxxxxxxxxxxxxxxxxxxxxx");
    }
}

启动:

16:35:48,920:INFO - Starting ProtocolHandler ["http-nio-9021"]
16:35:48,921:INFO - 1111111111111111,helloService=com.ebc.service.HelloService@67ed3522
16:35:48,938:INFO - Using a shared selector for servlet write/read
16:35:48,961:INFO - Started Application in 3.92 seconds (JVM running for 4.959)
16:35:48,964:INFO - PortalApplication is success!
xxxxxxxxxxxxxxxxxxxxxx
16:35:58,945:INFO - 22222222222222222

总结:

等待spring注入了所有bean后才执行执行。意味着,启动时,可以使用spring托管的任意bean。

而@PostConstract,无法做到。

原文地址:https://www.cnblogs.com/yaoyuan2/p/10267640.html