欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring事件监听机制

程序员文章站 2023-01-22 20:52:32
前言 Spring中的事件机制其实就是设计模式中的观察者模式,主要由以下角色构成: 1. 事件 2. 事件监听器(监听并处理事件) 3. 事件发布者(发布事件) 首先看一下监听器和发布者的接口定义 事件流转流程 初始化事件广播器 看一下这个方法 ,在IOC源码解析那篇文章已经把这个方法分析完了,所以 ......

前言

spring中的事件机制其实就是设计模式中的观察者模式,主要由以下角色构成:

  1. 事件
  2. 事件监听器(监听并处理事件)
  3. 事件发布者(发布事件)

首先看一下监听器和发布者的接口定义

public interface applicationlistener<e extends applicationevent> extends eventlistener {
      void onapplicationevent(e event);
  }
  
  public interface applicationeventpublisher {
    default void publishevent(applicationevent event) {
        publishevent((object) event);
    }
    void publishevent(object event);

}

事件流转流程

初始化事件广播器

看一下这个方法abstractapplicationcontext.refresh,在ioc源码解析那篇文章已经把这个方法分析完了,所以直接关注事件广播器和事件发布相关的逻辑即可

 public void refresh() throws beansexception, illegalstateexception {
        synchronized (this.startupshutdownmonitor) {
            // prepare this context for refreshing.
            preparerefresh();
 
            // tell the subclass to refresh the internal bean factory.
            configurablelistablebeanfactory beanfactory = obtainfreshbeanfactory();
 
            // prepare the bean factory for use in this context.
            preparebeanfactory(beanfactory);
 
            try {
                // allows post-processing of the bean factory in context subclasses.
                postprocessbeanfactory(beanfactory);
 
                // invoke factory processors registered as beans in the context.
                invokebeanfactorypostprocessors(beanfactory);
 
                // register bean processors that intercept bean creation.
                registerbeanpostprocessors(beanfactory);
 
                // initialize message source for this context.
                initmessagesource();
 
                // 初始化事件广播器
                initapplicationeventmulticaster();
 
                // initialize other special beans in specific context subclasses.
                onrefresh();
 
                // check for listener beans and register them.
                registerlisteners();
 
                // instantiate all remaining (non-lazy-init) singletons.
                finishbeanfactoryinitialization(beanfactory);
 
                // 发布事件
                finishrefresh();
            }
 
            catch (beansexception ex) {
                logger.warn("exception encountered during context initialization - cancelling refresh attempt", ex);
 
                // destroy already created singletons to avoid dangling resources.
                destroybeans();
 
                // reset 'active' flag.
                cancelrefresh(ex);
 
                // propagate exception to caller.
                throw ex;
            }
        }
}

protected void initapplicationeventmulticaster() {
        configurablelistablebeanfactory beanfactory = getbeanfactory();
        if (beanfactory.containslocalbean(application_event_multicaster_bean_name)) {
            this.applicationeventmulticaster =
                    beanfactory.getbean(application_event_multicaster_bean_name, applicationeventmulticaster.class);
            if (logger.isdebugenabled()) {
                logger.debug("using applicationeventmulticaster [" + this.applicationeventmulticaster + "]");
            }
        }
        else {
            this.applicationeventmulticaster = new simpleapplicationeventmulticaster(beanfactory);
            beanfactory.registersingleton(application_event_multicaster_bean_name, this.applicationeventmulticaster);
            if (logger.isdebugenabled()) {
                logger.debug("unable to locate applicationeventmulticaster with name '" +
                        application_event_multicaster_bean_name +
                        "': using default [" + this.applicationeventmulticaster + "]");
            }
        }
    }

可以看到如果没有自定义的事件广播器,默认是使用simpleapplicationeventmulticaster

发布事件

发布事件是在bean的初始化之后的

    protected void finishrefresh() {
        // initialize lifecycle processor for this context.
        initlifecycleprocessor();
 
        // propagate refresh to lifecycle processor first.
        getlifecycleprocessor().onrefresh();
 
        // 发布事件
        publishevent(new contextrefreshedevent(this));
 
        // participate in livebeansview mbean, if active.
        livebeansview.registerapplicationcontext(this);
    }


public void publishevent(applicationevent event) {
        assert.notnull(event, "event must not be null");
        if (logger.istraceenabled()) {
            logger.trace("publishing event in " + getdisplayname() + ": " + event);
        }
        //1. 获取到事件广播器,发布事件
        getapplicationeventmulticaster().multicastevent(event);
        //2. 如果存在父容器,父容器也将发布事件
        if (this.parent != null) {
            this.parent.publishevent(event);
        }
    }

具体的发布逻辑在multicastevent方法中

public void multicastevent(final applicationevent event) {
        //遍历执行listener,getapplicationlisteners调用abstractapplicationeventmulticaster父类方法
        for (final applicationlistener listener : getapplicationlisteners(event)) {
            executor executor = gettaskexecutor();
            if (executor != null) {
                executor.execute(new runnable() {
                    @override
                    public void run() {
                        listener.onapplicationevent(event);
                    }
                });
            }
            else {
                listener.onapplicationevent(event);
            }
        }
    }

可以看到也没啥特殊的,无非就是起个线程池去调用这些监听器的方法

而监听器的处理就看各个监听器的具体实现了