Spring源码解析(四)-事件处理器的初始化逻辑ApplicationEventMulticaster

在Spring中也有关于事件的处理,这些代码其实并不难也不是最重要的,但是有的时候确实能用上,所以这里拿出来讲讲,并且这个事件处理机制我最想要说明的是他的设计思想—观察者设计模式(关于设计模式后续会出专题讲解),下面我们直接进入源码,首先是初始化并注册一个事件管理类对象。

AbstractApplicationContext - 820 - N901
protected void initApplicationEventMulticaster() {
        ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
        if (beanFactory.containsLocalBean("applicationEventMulticaster")) {
            this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        } else {
        //N902  最重要的是这个地方,new了一个SimpleApplicationEventMulticaster对象,并且注册到了beanFactory中
            this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
            beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster);
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("No 'applicationEventMulticaster' bean, using [" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
            }
        }
    }
DefaultSingletonBeanRegistry - 48 - N902
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
		Assert.notNull(beanName, "Bean name must not be null");
		Assert.notNull(singletonObject, "Singleton object must not be null");
		synchronized (this.singletonObjects) {
			Object oldObject = this.singletonObjects.get(beanName);
			if (oldObject != null) {
				throw new IllegalStateException("Could not register object [" + singletonObject +
						"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
			}
			//这里将这个事件管理类对象加入到一级缓存中(循环依赖的源码会重点讲到三个缓存的作用)
			addSingleton(beanName, singletonObject);
		}
	}

事件管理类对象实例化并注册完成后,接下来就是需要将事件监听器注册进刚刚实例化出来的事件管理类

AbstractApplicationContext - 431 - N903
protected void registerListeners() {
        Iterator var1 = this.getApplicationListeners().iterator();
        while(var1.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var1.next();
            this.getApplicationEventMulticaster().addApplicationListener(listener);
        }
  //这个方法在前面见过几次了,主要就是通过类型,获取到前面扫描收集到的BD中属于这中类型的BeanName集合
        String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);
        String[] var7 = listenerBeanNames;
        int var3 = listenerBeanNames.length;
        for(int var4 = 0; var4 < var3; ++var4) {
        //这里遍历循环上面获取到的BeanName集合,将这些Bean加入到事件管理类对象中
            String listenerBeanName = var7[var4];
            //getApplicationEventMulticaster()是获取前面注册进入的事件管理类对象
            //N904 addApplicationListenerBean()方法是将BeanName放入事件管理类对象中的defaultRetriever这个对象中
            this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
        }
        Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
        this.earlyApplicationEvents = null;
        if (earlyEventsToProcess != null) {
            Iterator var9 = earlyEventsToProcess.iterator();
            while(var9.hasNext()) {
                ApplicationEvent earlyEvent = (ApplicationEvent)var9.next();
                this.getApplicationEventMulticaster().multicastEvent(earlyEvent);
            }
        }
    }
AbstractApplicationEventMulticaster - 81 - N904
public void addApplicationListenerBean(String listenerBeanName) {
        synchronized(this.retrievalMutex) {
//defaultRetriever这个对象里面有两个集合,一个是存事件监听类对象的集合applicationListeners,另一个是存事件监听类对象Name的集合applicationListenerBeans
            this.defaultRetriever.applicationListenerBeans.add(listenerBeanName);
            this.retrieverCache.clear();
        }
    }

事件监听类已经注册到事件管理器类对象中defaultRetriever这个对象applicationListenerBeans集合中了,接下来就是触发事件了。

AbstractApplicationContext - 178 - N905
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
        Assert.notNull(event, "Event must not be null");
        Object applicationEvent;
        if (event instanceof ApplicationEvent) {
            applicationEvent = (ApplicationEvent)event;
        } else {
            applicationEvent = new PayloadApplicationEvent(this, event);
            if (eventType == null) {
                eventType = ((PayloadApplicationEvent)applicationEvent).getResolvableType();
            }
        }
        if (this.earlyApplicationEvents != null) {
            this.earlyApplicationEvents.add(applicationEvent);
        } else { 
        //N906 这里拿到了所有处理该事件的事件监听类实例并调用其onApplicationEvent()方法
        this.getApplicationEventMulticaster().multicastEvent((ApplicationEvent)applicationEvent, eventType);
        }
        if (this.parent != null) {
            if (this.parent instanceof AbstractApplicationContext) {
                ((AbstractApplicationContext)this.parent).publishEvent(event, eventType);
            } else {
                this.parent.publishEvent(event);
            }
        }
    }
SimpleApplicationEventMulticaster - 54 - N906 
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
        ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
     //N907  getApplicationListeners()这个方法是获取到event事件相对应的事件监听对象
        Iterator var4 = this.getApplicationListeners(event, type).iterator();
        while(var4.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var4.next();
            Executor executor = this.getTaskExecutor();
            if (executor != null) {
                executor.execute(() -> {
                    this.invokeListener(listener, event);
                });
            } else {
            //N909  拿到了对应类型事件的事件监听器对象,则开始调用其中的onApplicationEvent()方法
                this.invokeListener(listener, event);
            }
        }
    }
AbstractApplicationEventMulticaster - 116 - N907
protected Collection<ApplicationListener<?>> getApplicationListeners(ApplicationEvent event, ResolvableType eventType) {
        Object source = event.getSource();
        Class<?> sourceType = source != null ? source.getClass() : null;
    //这里会通过规则计算出一个cacheKey,每个事件都对应一个cacheKey
        AbstractApplicationEventMulticaster.ListenerCacheKey cacheKey = new AbstractApplicationEventMulticaster.ListenerCacheKey(eventType, sourceType);
    //首先会通过cacheKey从retrieverCache拿到一个retriever
        AbstractApplicationEventMulticaster.ListenerRetriever retriever = (AbstractApplicationEventMulticaster.ListenerRetriever)this.retrieverCache.get(cacheKey);
    //如果retriever不为空则直接拿到里面的监听器对象返回即可
        if (retriever != null) {
            return retriever.getApplicationListeners();
        } else if (this.beanClassLoader == null || ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) && (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader))) {
            synchronized(this.retrievalMutex) {
      //首次触发事件,retriever肯定为null,所以进入这里,这里有一个synchronized锁,然后重新从retrieverCache中拿关于这个cacheKey对应的retriever,如果不为空直接拿到里面的监听器对象返回即可,
      //值得一提的是,上面为什么要两次从cache拿同一个key的值呢?因为很有可能多个线程在获取锁而等待时,其它线程已经将retriever对象放入到cache中,此时就直接可以拿,这也是【线程安全的单例模型】
                retriever = (AbstractApplicationEventMulticaster.ListenerRetriever)this.retrieverCache.get(cacheKey);
                if (retriever != null) {
                //retriever不为空,直接返回
                    return retriever.getApplicationListeners();
                } else {
              //retriever为null,则直接实例化一个对象赋值给retriever变量
                    retriever = new AbstractApplicationEventMulticaster.ListenerRetriever(true);
          //N908  这个方法主要是完成从所有的listener中选出处理当前事件event的listener
                    Collection<ApplicationListener<?>> listeners = this.retrieveApplicationListeners(eventType, sourceType, retriever);
                //在N908中返回了满足条件的
                    this.retrieverCache.put(cacheKey, retriever);
                    return listeners;
                }
            }
        } else {
            return this.retrieveApplicationListeners(eventType, sourceType, (AbstractApplicationEventMulticaster.ListenerRetriever)null);
        }
    }
AbstractApplicationEventMulticaster - 140 - N908
private Collection<ApplicationListener<?>> retrieveApplicationListeners(ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable AbstractApplicationEventMulticaster.ListenerRetriever retriever) {
        List<ApplicationListener<?>> allListeners = new ArrayList();
        LinkedHashSet listeners;
        LinkedHashSet listenerBeans;
        synchronized(this.retrievalMutex) {
        //listener是所有事件处理类的实例对象集合 listenerBeans是所有事件监听类的BeanName
            listeners = new LinkedHashSet(this.defaultRetriever.applicationListeners);
            listenerBeans = new LinkedHashSet(this.defaultRetriever.applicationListenerBeans);
        }
        //首先会遍历所有的实例对象,将处理当前事件类型的listener加入到最后返回的集合allListeners中
        Iterator var7 = listeners.iterator();
        while(var7.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var7.next();
            //supportsEvent()方法就是检测listener是否为处理eventType的监听器
            if (this.supportsEvent(listener, eventType, sourceType)) {
                if (retriever != null) {
                //并且还需要将这个listener加入到retriever的applicationListeners集合中
                    retriever.applicationListeners.add(listener);
                }
                allListeners.add(listener);
            }
        }
    //处理完listener的所有实例对象,接下来就是从所有事件监听类的BeanName,找到能够处理当前event的BeanName
    //前面我们看到是将事件监听器BeanName加入到事件管理类中的applicationListenerBeans这个集合中的。
    //所以第一次就是会走入下面这个if块
        if (!listenerBeans.isEmpty()) {
            BeanFactory beanFactory = this.getBeanFactory();
            Iterator var15 = listenerBeans.iterator();
            while(var15.hasNext()) {
                String listenerBeanName = (String)var15.next();
                try {
                //从beanFactory中拿到这个BeanName的class
                    Class<?> listenerType = beanFactory.getType(listenerBeanName);
                    if (listenerType == null || this.supportsEvent(listenerType, eventType)) {
                    //如果这个Class满足处理当前event,就通过getBean实例化这个对象
                        ApplicationListener<?> listener = (ApplicationListener)beanFactory.getBean(listenerBeanName, ApplicationListener.class);
                        //判断是否在allListenters返回集合中,是否包含这个对象。判断是否满足处理当前的事件
                        if (!allListeners.contains(listener) && this.supportsEvent(listener, eventType, sourceType)) {
                   //满足上述条件后,判断是否为单例,如果是,则实例对象加入到applicationListeners,不是则BeanName加入applicationListenerBeans,这也是为什么要用两个集合来存,为了满足单例和非单例
                            if (retriever != null) {
                                if (beanFactory.isSingleton(listenerBeanName)) {
                                    retriever.applicationListeners.add(listener);
                                } else {
                                    retriever.applicationListenerBeans.add(listenerBeanName);
                                }
                            }
                            //最后加入到返回集合allListeners中
                            allListeners.add(listener);
                        }
                    }
                } catch (NoSuchBeanDefinitionException var13) {
                }
            }
        }
        AnnotationAwareOrderComparator.sort(allListeners);
        if (retriever != null && retriever.applicationListenerBeans.isEmpty()) {
            retriever.applicationListeners.clear();
            retriever.applicationListeners.addAll(allListeners);
        }
        //返回allListeners集合,并且此时retriever对象中也存了关于这个事件的所有监听对象listener
        return allListeners;
    }
SimpleApplicationEventMulticaster - 76 - N909
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
        ErrorHandler errorHandler = this.getErrorHandler();
        if (errorHandler != null) {
            try {
                this.doInvokeListener(listener, event);
            } catch (Throwable var5) {
                errorHandler.handleError(var5);
            }
        } else {
        //N910  这个方法里面调用了监听器的onApplicationEvent()方法
            this.doInvokeListener(listener, event);
        }
    }
SimpleApplicationEventMulticaster - 90 - N910
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
        try {
        //这里执行了onApplicationEvent方法,这个方法就是我们在listener实现类中实现的方法
            listener.onApplicationEvent(event);
        } catch (ClassCastException var6) {
            String msg = var6.getMessage();
            if (msg != null && !this.matchesClassCastMessage(msg, event.getClass())) {
                throw var6;
            }
            Log logger = LogFactory.getLog(this.getClass());
            if (logger.isDebugEnabled()) {
                logger.debug("Non-matching event type for listener: " + listener, var6);
            }
        }
    }

遍历调用完所有符合条件的监听器的onApplicationEvent()方法后,整个事件相关的处理也就结束了。这里面涉及到了观察者模式,线程安全的单例模式等设计模式,这也是学习源码最该学习的东西—设计思想。

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值