zoukankan      html  css  js  c++  java
  • spring boot 之监听器ApplicationListener

    监听器
    ApplicationListener 就是spring的监听器,能够用来监听事件,典型的观察者模式。
    ApplicationListener和ContextRefreshedEvent一般都是成对出现的
    在IOC容器的启动过程中,当所有的bean都已经处理完成之后,spring ioc容器会有一个发布事件的动作。从AbstractApplicationContext 的源码中可以看出:

    /**
     * Finish the refresh of this context, invoking the LifecycleProcessor's
     * onRefresh() method and publishing the
     * {@link org.springframework.context.event.ContextRefreshedEvent}.
     */
    protected void finishRefresh() {
       // Clear context-level resource caches (such as ASM metadata from scanning).
       clearResourceCaches();
    
       // Initialize lifecycle processor for this context.
       initLifecycleProcessor();
    
       // Propagate refresh to lifecycle processor first.
       getLifecycleProcessor().onRefresh();
    
       // Publish the final event.
       publishEvent(new ContextRefreshedEvent(this));
    
       // Participate in LiveBeansView MBean, if active.
       LiveBeansView.registerApplicationContext(this);
    }

    这样,当ioc容器加载处理完相应的bean之后,也给我们提供了一个机会(先有InitializingBean,后有ApplicationListener<ContextRefreshedEvent>),可以去做一些自己想做的事。其实这也就是spring ioc容器给提供的一个扩展的地方。我们可以这样使用这个扩展机制。
    一个最简单的方式就是,让我们的bean实现ApplicationListener接口,这样当发布事件时,spring 的ioc容器就会以容器的实例对象作为事件源类,并从中找到事件的监听者,此时ApplicationListener接口实例中的onApplicationEvent(E event)方法就会被调用,我们的逻辑代码就会写在此处。这样我们的目的就达到了。但这也带来一个思考,有人可能会想,这样的代码我们也可以通过实现spring 的InitializingBean接口来实现啊,也会被spring 容器去自动调用,但是大家应该想到,如果我们现在想做的事,是必须要等到所有的bean都被处理完成之后再进行,此时InitializingBean接口的实现就不合适了,所以需要深刻理解事件机制的应用场合。
    系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)
    这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理
    简单示例代码如下:

    package com.example.demo.init;
    
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ZkServerInit implements ApplicationListener<ContextRefreshedEvent> {
        @Override
        public void onApplicationEvent(ContextRefreshedEvent context) {
            if (null == context.getApplicationContext().getParent()) {
                System.err.println("初始化zkServer...");
                // 初始化逻辑...
                System.err.println("初始化zkServer完成...");
            }
        }
    }
  • 相关阅读:
    2019武汉大学数学专业考研真题(回忆版)
    矩阵求导与投影梯度相关问题
    Coxeter积分计算
    常微分方程
    一些个人偏好的书籍
    Angular的表单组件
    Angular的第一个组件
    Angular的第一个helloworld
    Angular入门
    handlebars——另外一个模板引擎
  • 原文地址:https://www.cnblogs.com/weianlai/p/11351965.html
Copyright © 2011-2022 走看看