spring在容器中使用了观察者模式:
一、spring事件:ApplicationEvent,该抽象类继承了EventObject类,jdk建议所有的事件都应该继承自EventObject。
二、spring事件监听器:ApplicationLisener,该接口继承了EventListener接口,jdk建议所有的事件监听器都应该继承EventListener。
Java代码 
1public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { 2 3 /** 4 * Handle an application event. 5 * @param event the event to respond to 6 */ 7 void onApplicationEvent(E event); 8}
三、spring事件发布:ApplicationEventPublisher 。 ApplicationContext继承了该接口,在ApplicationContext的抽象类AbstractApplicationContext中做了实现。
1package org.springframework.context; 2 3public interface ApplicationEventPublisher { 4 5/** * Notify all <strong>matching</strong> listeners registered with this * application of an application event. Events may be framework events * (such as RequestHandledEvent) or application-specific events. * @param event the event to publish * @see org.springframework.web.context.support.RequestHandledEvent */ 6 7 void publishEvent(ApplicationEvent var1); 8 9 void publishEvent(Object var1); 10}

AbstractApplicationContext类中publishEvent方法实现:
1/** 2 * Publish the given event to all listeners. 3 * <p>Note: Listeners get initialized after the MessageSource, to be able 4 * to access it within listener implementations. Thus, MessageSource 5 * implementations cannot publish events. 6 * @param event the event to publish (may be an {@link ApplicationEvent} 7 * or a payload object to be turned into a {@link PayloadApplicationEvent}) 8 */ 9 @Override 10 public void publishEvent(Object event) { 11 publishEvent(event, null); 12 } 13 14 /** 15 * Publish the given event to all listeners. 16 * @param event the event to publish (may be an {@link ApplicationEvent} 17 * or a payload object to be turned into a {@link PayloadApplicationEvent}) 18 * @param eventType the resolved event type, if known 19 * @since 4.2 20 */ 21 protected void publishEvent(Object event, @Nullable ResolvableType eventType) { 22 Assert.notNull(event, "Event must not be null"); 23 if (logger.isTraceEnabled()) { 24 logger.trace("Publishing event in " + getDisplayName() + ": " + event); 25 } 26 27 // Decorate event as an ApplicationEvent if necessary 28 ApplicationEvent applicationEvent; 29 if (event instanceof ApplicationEvent) { 30 applicationEvent = (ApplicationEvent) event; 31 } 32 else { 33 applicationEvent = new PayloadApplicationEvent<>(this, event); 34 if (eventType == null) { 35 eventType = ((PayloadApplicationEvent) applicationEvent).getResolvableType(); 36 } 37 } 38 39 // Multicast right now if possible - or lazily once the multicaster is initialized 40 if (this.earlyApplicationEvents != null) { 41 this.earlyApplicationEvents.add(applicationEvent); 42 } 43 else { //事件广播委托给ApplicationEventMulticaster来进行 44 getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); 45 } 46 47 // Publish event via parent context as well... 48 if (this.parent != null) { 49 if (this.parent instanceof AbstractApplicationContext) { 50 ((AbstractApplicationContext) this.parent).publishEvent(event, eventType); 51 } 52 else { 53 this.parent.publishEvent(event); 54 } 55 } 56 }
由上代码可知,AbstractApplicationContext类并没有具体的做事件广播,而是委托给ApplicationEventMulticaster来进行,ApplicationEventMulticaster的multicastEvent()方法实现如下:
1 @Override 2 public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { 3 ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); 4 for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) { 5 Executor executor = getTaskExecutor(); 6 if (executor != null) { 7 executor.execute(() -> invokeListener(listener, event)); 8 } 9 else { 10 invokeListener(listener, event); 11 } 12 } 13 } 14 15protected void invokeListener(ApplicationListener listener, ApplicationEvent event) { 16 ErrorHandler errorHandler = this.getErrorHandler(); 17 if (errorHandler != null) { 18 try { 19 listener.onApplicationEvent(event); 20 } catch (Throwable var6) { 21 errorHandler.handleError(var6); 22 } 23 } else { 24 try { 25 listener.onApplicationEvent(event); 26 } catch (ClassCastException var5) { 27 LogFactory.getLog(this.getClass()).debug("Non-matching event type for listener: " + listener, var5); 28 } 29 } 30 31 }
获得listener集合,遍历listener触发事件Executor接口有多个实现类,可以支持同步或异步广播事件。
问题:spring容器是怎么根据事件去找到事件对应的事件监听器呢?
一、入口
private ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml");
二、生成Spring上下文ApplicationContext
1public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { 2 super(parent); 3 this.setConfigLocations(configLocations); 4 if (refresh) { 5 this.refresh(); 6 } 7 8 }
三、调用spring容器初始化方法
1public void refresh() throws BeansException, IllegalStateException { 2 synchronized (this.startupShutdownMonitor) { 3 // Prepare this context for refreshing. 4 prepareRefresh(); 5 6 // Tell the subclass to refresh the internal bean factory. 7 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 8 9 // Prepare the bean factory for use in this context. 10 prepareBeanFactory(beanFactory); 11 12 try { 13 // Allows post-processing of the bean factory in context subclasses. 14 postProcessBeanFactory(beanFactory); 15 16 // Invoke factory processors registered as beans in the context. 17 invokeBeanFactoryPostProcessors(beanFactory); 18 19 // Register bean processors that intercept bean creation. 20 registerBeanPostProcessors(beanFactory); 21 22 // Initialize message source for this context. 23 initMessageSource(); 24 25 26 //初始化一个事件注册表 27 // Initialize event multicaster for this context. 28 initApplicationEventMulticaster(); 29 30 // Initialize other special beans in specific context subclasses. 31 onRefresh(); 32 33 // 初始化事件监听器 34 // Check for listener beans and register them. 35 registerListeners(); 36 // 实例化所有单例对象,其中包括默认注册表 37 // Instantiate all remaining (non-lazy-init) singletons. 38 finishBeanFactoryInitialization(beanFactory); 39 // 发布事件 40 // Last step: publish corresponding event. 41 finishRefresh(); 42 } 43 44 catch (BeansException ex) { 45 if (logger.isWarnEnabled()) { 46 logger.warn("Exception encountered during context initialization - " + 47 "cancelling refresh attempt: " + ex); 48 } 49 50 // Destroy already created singletons to avoid dangling resources. 51 destroyBeans(); 52 53 // Reset 'active' flag. 54 cancelRefresh(ex); 55 56 // Propagate exception to caller. 57 throw ex; 58 } 59 60 finally { 61 // Reset common introspection caches in Spring's core, since we 62 // might not ever need metadata for singleton beans anymore... 63 resetCommonCaches(); 64 } 65 } 66 }
3.1 initApplicationEventMulticaster()方法代码
1protected void initApplicationEventMulticaster() { 2 ConfigurableListableBeanFactory beanFactory = this.getBeanFactory(); 3 //先查找BeanFactory配置文件中是否有ApplicationEventMulticaster 4 if (beanFactory.containsLocalBean("applicationEventMulticaster")) { 5 this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class); 6 if (this.logger.isDebugEnabled()) { 7 this.logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); 8 } 9 } else {// 如果beanFactory中没有,则创建一个SimpleApplicationEventMulticaster 10 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); 11 beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster); 12 if (this.logger.isDebugEnabled()) { 13 this.logger.debug("Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [" + this.applicationEventMulticaster + "]"); 14 } 15 } 16 17 }
spring先从beanFactory中获取ApplicationEventMulticaster,如果没有自定义,则创建一个SimpleApplicationEventMulticaster。
ApplicationEventMulticaster包含以下属性:defaultRetriever即为注册表,注册监听事件的相关消息; retrieverCache用来做defaultRetriever的缓存。
1public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware { 2 private final AbstractApplicationEventMulticaster.ListenerRetriever defaultRetriever = new AbstractApplicationEventMulticaster.ListenerRetriever(false); 3 final Map<AbstractApplicationEventMulticaster.ListenerCacheKey, AbstractApplicationEventMulticaster.ListenerRetriever> retrieverCache = new ConcurrentHashMap(64); 4 private ClassLoader beanClassLoader; 5 private BeanFactory beanFactory; 6 private Object retrievalMutex; 7}
ListenerRetriever的数据结构如下:applicationListeners用来存放监听事件, applicationListenerBeans为存放监听事件的类名称。
1private class ListenerRetriever { 2 public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet(); 3 public final Set<String> applicationListenerBeans = new LinkedHashSet(); 4 private final boolean preFiltered;
ListenerCacheKey的数据结构如下:eventType是事件类型,sourceType是事件的源类型,即为事件的构造函数的参数类型。
1private static class ListenerCacheKey { 2 private final ResolvableType eventType; 3 private final Class<?> sourceType;
3.2 registerListeners()方法代码
初始化注册表以后,则把事件注册到注册表中,registerListeners()
1protected void registerListeners() { 2 //获取所有的listener的迭代器 3 Iterator var1 = this.getApplicationListeners().iterator(); 4 5 while(var1.hasNext()) { 6 ApplicationListener<?> listener = (ApplicationListener)var1.next(); 7 //把获取所有的listener, 把事件的bean放到ApplicationEventMulticaster中的ApplicationListener 8 this.getApplicationEventMulticaster().addApplicationListener(listener); 9 } 10 11 String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false); 12 String[] var7 = listenerBeanNames; 13 int var3 = listenerBeanNames.length; 14 15 for(int var4 = 0; var4 < var3; ++var4) { 16 String listenerBeanName = var7[var4]; 17 //把事件的名称放到ApplicationListenerBean里去 this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); 18 } 19 20 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; 21 this.earlyApplicationEvents = null; 22 if (earlyEventsToProcess != null) { 23 Iterator var9 = earlyEventsToProcess.iterator(); 24 25 while(var9.hasNext()) { 26 ApplicationEvent earlyEvent = (ApplicationEvent)var9.next(); 27 this.getApplicationEventMulticaster().multicastEvent(earlyEvent); 28 } 29 } 30 31 } 32 333.3 finishBeanFactoryInitialization(beanFactory) 具体会执行到下面的方法,会把AbstractApplicationEventMulticaster的defaultRetriever属性赋值。 执行PostProcessorRegistrationDelegate类的postProcessAfterInitialization()方法: 34 35public Object postProcessAfterInitialization(Object bean, String beanName) { 36 if (this.applicationContext != null && bean instanceof ApplicationListener) { 37 Boolean flag = (Boolean)this.singletonNames.get(beanName); 38 if (Boolean.TRUE.equals(flag)) { 39 this.applicationContext.addApplicationListener((ApplicationListener)bean); 40 } else if (flag == null) { 41 if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) { 42 logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " + "but is not reachable for event multicasting by its containing ApplicationContext " + "because it does not have singleton scope. Only top-level listener beans are allowed " + "to be of non-singleton scope."); 43 } 44 45 this.singletonNames.put(beanName, Boolean.FALSE); 46 } 47 } 48 49 return bean; 50 }
执行AbstractApplicationContext类的addApplicationListener()方法:
1 public void addApplicationListener(ApplicationListener<?> listener) { 2 if (this.applicationEventMulticaster != null) { 3 this.applicationEventMulticaster.addApplicationListener(listener); 4 } else { 5 this.applicationListeners.add(listener); 6 } 7 } 8 9执行AbstractApplicationEventMulticaster类的addApplicationListener()方法 10 11public void addApplicationListener(ApplicationListener<?> listener) { 12 Object var2 = this.retrievalMutex; 13 synchronized(this.retrievalMutex) { 14 this.defaultRetriever.applicationListeners.add(listener); 15 this.retrieverCache.clear(); 16 } 17 }
【spring根据反射机制,通过方法getBeansOfType()获取所有继承了ApplicationListener接口的监听器,然后把监听器全放到注册表里,所以我们可以在spring配置文件中配置自定义的监听器,在spring初始化的时候会把监听器自动注册到注册表中。】
13.4 finishRefresh()里面执行发布事件。 2 3protected void finishRefresh() { 4 this.initLifecycleProcessor(); 5 this.getLifecycleProcessor().onRefresh(); 6 this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this))); 7 LiveBeansView.registerApplicationContext(this); 8 }
在applicationContext发布事件的时候。
1public void publishEvent(ApplicationEvent event) { 2 this.publishEvent(event, (ResolvableType)null); 3 } 4 5 public void publishEvent(Object event) { 6 this.publishEvent(event, (ResolvableType)null); 7 } 8 9 protected void publishEvent(Object event, ResolvableType eventType) { 10 Assert.notNull(event, "Event must not be null"); 11 if (this.logger.isTraceEnabled()) { 12 this.logger.trace("Publishing event in " + this.getDisplayName() + ": " + event); 13 } 14 15 Object applicationEvent; 16 if (event instanceof ApplicationEvent) { 17 applicationEvent = (ApplicationEvent)event; 18 } else { 19 applicationEvent = new PayloadApplicationEvent(this, event); 20 if (eventType == null) { 21 eventType = ((PayloadApplicationEvent)applicationEvent).getResolvableType(); 22 } 23 } 24 25 if (this.earlyApplicationEvents != null) { 26 this.earlyApplicationEvents.add(applicationEvent); 27 } else { 28 // 调用ApplicationEventMulticaster的multicastEvent()方法 this.getApplicationEventMulticaster().multicastEvent((ApplicationEvent)applicationEvent, eventType); 29 } 30 31 if (this.parent != null) { 32 if (this.parent instanceof AbstractApplicationContext) { 33 ((AbstractApplicationContext)this.parent).publishEvent(event, eventType); 34 } else { 35 this.parent.publishEvent(event); 36 } 37 } 38 39 }
AbstractApplicationContext类并没有具体的做事件广播,而是委托给ApplicationEventMulticaster来进行。
ApplicationEventMulticaster的方法multicastEvent()为:
1public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) { 2 ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event); 3 Iterator var4 = this.getApplicationListeners(event, type).iterator(); 4 5 while(var4.hasNext()) { 6 final ApplicationListener<?> listener = (ApplicationListener)var4.next(); 7 Executor executor = this.getTaskExecutor(); 8 if (executor != null) { 9 executor.execute(new Runnable() { 10 public void run() { 11 SimpleApplicationEventMulticaster.this.invokeListener(listener, event); 12 } 13 }); 14 } else { 15 this.invokeListener(listener, event); 16 } 17 } 18 19 }
根据事件和类型获取所有的监听器方法: getApplicationListeners()
1protected Collection<ApplicationListener<?>> getApplicationListeners(ApplicationEvent event, ResolvableType eventType) { 2 Object source = event.getSource(); 3 Class<?> sourceType = source != null ? source.getClass() : null; 4 AbstractApplicationEventMulticaster.ListenerCacheKey cacheKey = new AbstractApplicationEventMulticaster.ListenerCacheKey(eventType, sourceType); 5 AbstractApplicationEventMulticaster.ListenerRetriever retriever = (AbstractApplicationEventMulticaster.ListenerRetriever)this.retrieverCache.get(cacheKey); //从缓存里查找ListenerRetriever 6 if (retriever != null) { 7 return retriever.getApplicationListeners(); 8 } else if (this.beanClassLoader == null || ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) && (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader))) { 9 Object var7 = this.retrievalMutex; 10 synchronized(this.retrievalMutex) { 11 retriever = (AbstractApplicationEventMulticaster.ListenerRetriever)this.retrieverCache.get(cacheKey); 12 if (retriever != null) { 13 return retriever.getApplicationListeners(); 14 } else { //如果缓存里不存在,则去获得 15 retriever = new AbstractApplicationEventMulticaster.ListenerRetriever(true); 16 Collection<ApplicationListener<?>> listeners = this.retrieveApplicationListeners(eventType, sourceType, retriever); 17 this.retrieverCache.put(cacheKey, retriever); 18 return listeners; 19 } 20 } 21 } else { 22 return this.retrieveApplicationListeners(eventType, sourceType, (AbstractApplicationEventMulticaster.ListenerRetriever)null); 23 } 24 } 25 26private Collection<ApplicationListener<?>> retrieveApplicationListeners(ResolvableType eventType, Class<?> sourceType, AbstractApplicationEventMulticaster.ListenerRetriever retriever) { 27 LinkedList<ApplicationListener<?>> allListeners = new LinkedList(); 28 Object var7 = this.retrievalMutex; 29 LinkedHashSet listeners; 30 LinkedHashSet listenerBeans; 31 synchronized(this.retrievalMutex) { //获取注册表里所有的listener, defaultRetriever在前面已被赋值 32 listeners = new LinkedHashSet(this.defaultRetriever.applicationListeners); 33 listenerBeans = new LinkedHashSet(this.defaultRetriever.applicationListenerBeans); 34 } 35 36 Iterator var14 = listeners.iterator(); 37 38 while(var14.hasNext()) { 39 ApplicationListener<?> listener = (ApplicationListener)var14.next(); //根据事件类型,事件源类型,获取所需要的监听事件 40 if (this.supportsEvent(listener, eventType, sourceType)) { 41 if (retriever != null) { 42 retriever.applicationListeners.add(listener); 43 } 44 45 allListeners.add(listener); 46 } 47 } 48 49 if (!listenerBeans.isEmpty()) { 50 BeanFactory beanFactory = this.getBeanFactory(); 51 Iterator var16 = listenerBeans.iterator(); 52 53 while(var16.hasNext()) { 54 String listenerBeanName = (String)var16.next(); 55 56 try { 57 Class<?> listenerType = beanFactory.getType(listenerBeanName); 58 if (listenerType == null || this.supportsEvent(listenerType, eventType)) { 59 ApplicationListener<?> listener = (ApplicationListener)beanFactory.getBean(listenerBeanName, ApplicationListener.class); 60 if (!allListeners.contains(listener) && this.supportsEvent(listener, eventType, sourceType)) { 61 if (retriever != null) { 62 retriever.applicationListenerBeans.add(listenerBeanName); 63 } 64 65 allListeners.add(listener); 66 } 67 } 68 } catch (NoSuchBeanDefinitionException var13) { 69 ; 70 } 71 } 72 } 73 74 AnnotationAwareOrderComparator.sort(allListeners); 75 return allListeners; 76 }
配合上面的注解,即可理解,根据事件和事件类型找到对应的监听器,那么如何根据事件类型找到对应的监听器呢?
上面方法中的supportsEvent(listener, eventType, sourceType)方法实现了根据事件类型查找对应的监听器,代码具体实现为:
1protected boolean supportsEvent(ApplicationListener<?> listener, ResolvableType eventType, Class<?> sourceType) { 2 GenericApplicationListener smartListener = listener instanceof GenericApplicationListener ? (GenericApplicationListener)listener : new GenericApplicationListenerAdapter(listener); 3 return ((GenericApplicationListener)smartListener).supportsEventType(eventType) && ((GenericApplicationListener)smartListener).supportsSourceType(sourceType); 4 }
如上可知:上面方法的返回结果跟方法smartListener.supportsEventType(eventType)和smartListener.supportsSourceType(sourceType)有关。
smartListener.supportsEventType(eventType)方法实现为:
1public boolean supportsEventType(ResolvableType eventType) { 2 if (this.delegate instanceof SmartApplicationListener) { 3 Class<? extends ApplicationEvent> eventClass = eventType.getRawClass(); 4 return ((SmartApplicationListener)this.delegate).supportsEventType(eventClass); 5 } else { 6 return this.declaredEventType == null || this.declaredEventType.isAssignableFrom(eventType); 7 } 8 }
该方法主要的逻辑就是根据事件类型判断是否和监听器参数泛型的类型是否一致。
1public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { 2 3 /** 4 * Handle an application event. 5 * @param event the event to respond to 6 */ 7 void onApplicationEvent(E event); 8 9}
在定义自己的监听器要明确指定参数泛型,表明该监听器支持的事件,如果不指明具体的泛型,则没有监听器监听事件。
smartListener.supportsSourceType(sourceType)方法的实现为:
1public boolean supportsSourceType(Class<?> sourceType) { 2 return this.delegate instanceof SmartApplicationListener ? ((SmartApplicationListener)this.delegate).supportsSourceType(sourceType) : true; 3 }
以上是spring的事件体系。
四、自定义事件和监听器
我们可以使用spring的事件广播体系,自定义自己的事件:
自定义事件,继承ApplicationEvent:
1public class DIYEvent extends ApplicationEvent { 2 private static final long serialVersionUID = 7099057708183571977L; 3 4 public DIYEvent(String source) { 5 super(source); 6 } 7}
自定义listener,继承ApplicationListener
1@Component 2public class DIYListener implements ApplicationListener<DIYEvent> { 3 @Override 4 public void onApplicationEvent(DIYEvent diyEvent) { 5 System.out.println("自定义监听器执行"); 6 System.out.println(diyEvent.getSource()); 7 } 8}
测试触发事件:
1public class DIYTest{ 2 private ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml"); 3 4 @Test 5 public void diyTest(){ 6 applicationContext.publishEvent(new DIYEvent("测试数据")); 7 } 8}
获取ApplicationContext,发布事件。
调试结果:
1自定义监听器执行 2 3测试数据