Spring项目启动后执行操作:ContextRefreshedEvent和ApplicationReadyEvent

一、Spring boot运行时,会发送以下事件

1. ApplicationStartingEvent 

2. ApplicationEnvironmentPreparedEvent:当Environment已经准备好,在context 创建前

3. ApplicationContextInitializedEvent:在ApplicationContext 创建和ApplicationContextInitializer都被调用后,但是bean definition没有被加载前

4. ApplicationPreparedEvent:bean definition已经加载,但是没有refresh

5. ApplicationStartedEvent: context 已经被refresh, 但是application 和command-line 的runner都没有被调用

6. AvailabilityChangeEvent

7. ApplicationReadyEvent: application 和command-line 的runner都被调用后触发

8. AvailabilityChangeEvent

9. ApplicationFailedEvent: 启动失败触发

另外,会在ApplicationPreparedEvent之后和ApplicationStartedEvent之前发送

ContextRefreshedEvent

二、项目启动后需要执行某个操作

1. 实现ApplicationListener<E extends ApplicationEvent>接口

2. ApplicationEvent的子类可以是ApplicationReadyEvent或者ContextRefreshedEvent

3. ApplicationReadyEvent的示例

@Component
@Slf4j
public class ApplicationInit implements ApplicationListener<ApplicationReadyEvent> {
    
    // 项目启动后预热JSON
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(123L);
        userInfo.setChannel("hello");
        String userJson = JSON.toJSONString(userInfo);
        JSON.parseObject(userJson, UserInfo.class);
    }
}

三、ContextRefreshedEvent多次执行的问题

1. web应用会出现父子容器,这样就会触发两次

2. 解决方法:ApplicationListener<ContextRefreshedEvent> 应该和 ApplicationContext 一对一

参考:

https://www.jianshu.com/p/4cf382e725b3

https://blog.csdn.net/zollty/article/details/86137380

原文地址:https://www.cnblogs.com/june0816/p/14173225.html