美文网首页
Application 事件与监听器

Application 事件与监听器

作者: 尚水杨 | 来源:发表于2020-08-04 18:52 被阅读0次

    事件的监听

    由于有些事件是在ApplicationContext创建前就发生了,所以不可以通过@Bean的方式来注册监听器。
    可以通过如下方式:

    1. SpringApplication.addListeners(…​)
    2. SpringApplicationBuilder.listeners(…​)
    3. 在META-INF/spring.factories中配置
    org.springframework.context.ApplicationListener=org.ysy.study.springboot.startup.DemoListener
    

    DemoListener代码

    import org.springframework.context.ApplicationEvent;
    import org.springframework.context.ApplicationListener;
    
    public class DemoListener implements ApplicationListener<ApplicationEvent> {
        private Logger logger= LoggerFactory.getLogger(this.getClass());
        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            logger.info("event==> {}",event.toString());
        }
    }
    

    事件

    当一个Application运行时,会发送如下事件:

    1. ApplicationStartingEvent
      运行run在注册完监听器与初始化器后,处理其他前触发。(测试的时候发现监听不到这个事件,暂时还不知道原因)
    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
      带上LivenessState.CORRECT标志,标识应用是活的。
    7. ApplicationReadyEvent
      application 和command-line 的runner都被调用后。
    8. AvailabilityChangeEvent
      带上ReadinessState.ACCEPTING_TRAFFIC标志,标识应用可以提供服务。
    9. ApplicationFailedEvent
      启动过程中,抛异常了。

    另外还在如下事件在ApplicationPreparedEvent 之后和ApplicationStartedEvent之前发送

    1. WebServerInitializedEvent
      WebServer已经准备好
      1.1 ServletWebServerInitializedEvent
      servlet 准备好
      1.2 ReactiveWebServerInitializedEvent
      reactive 准备好
    2. ContextRefreshedEvent
      ApplicationContext已经refresh。

    相关文章

      网友评论

          本文标题:Application 事件与监听器

          本文链接:https://www.haomeiwen.com/subject/upiwrktx.html