一、Spring boot运行启动过程中,会发送以下事件
1. ApplicationStartingEvent
2. ApplicationEnvironmentPreparedEvent:当Environment已经准备好,在context 创建前
3. ApplicationContextInitializedEvent:在ApplicationContext 创建和ApplicationContextInitializer都被调用后,但是bean definition没有被加载前
4. ApplicationPreparedEvent:bean definition已经加载,但是ApplicationContext 没有refresh
5.ContextRefreshedEvent :ApplicationContext已经refresh
6. ApplicationStartedEvent: ApplicationContext已经refresh,但是application 和command-line 的runner都没有被调用
7. AvailabilityChangeEvent
8. ApplicationReadyEvent: application 和command-line 的runner都被调用后触发
9. AvailabilityChangeEvent
10. ApplicationFailedEvent: 启动失败触发
二、Spring启动过程中需要执行某个操作时
1. 实现ApplicationListener<E extends ApplicationEvent>接口
2. ApplicationEvent的子类可以是ApplicationReadyEvent或者ContextRefreshedEvent
3. ApplicationStartedEvent 的示例
@Component
@Slf4j
public class ApplicationInit implements ApplicationListener<ApplicationStartedEvent> {
// Spring容器加载完成所有bean后,执行
@Override
public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
log.info("执行自定义业务逻辑...");
}
}
三、CommandLineRunner和ApplicationRunner 接口
Spring容器完成初始化,执行业务逻辑。两者区别:参数不同
@Slf4j
@Component
public class MyRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 逻辑代码
}
}
@Component
@Sl4j
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args){
// 逻辑代码
}
}
参考:SpringBoot 启动时执行:CommandLineRunner、ApplicationRunner 和 ApplicationListener_Quantum_Wu的博客-CSDN博客