目錄java
在講解事件監聽機制前,咱們先回顧下設計模式中的觀察者模式,由於事件監聽機制能夠說是在典型觀察者模式基礎上的進一步抽象和改進。咱們能夠在JDK或者各類開源框架好比Spring中看到它的身影,從這個意義上說,事件監聽機制也能夠看作一種對傳統觀察者模式的具體實現,不一樣的框架對其實現方式會有些許差異。spring
典型的觀察者模式將有依賴關係的對象抽象爲了觀察者和主題兩個不一樣的角色,多個觀察者同時觀察一個主題,二者只經過抽象接口保持鬆耦合狀態,這樣雙方能夠相對獨立的進行擴展和變化:好比能夠很方便的增刪觀察者,修改觀察者中的更新邏輯而不用修改主題中的代碼。可是這種解耦進行的並不完全,這具體體如今如下幾個方面:數據庫
咱們能夠把主題(Subject)替換成事件(event),把對特定主題進行觀察的觀察者(Observer)替換成對特定事件進行監聽的監聽器(EventListener),而把原有主題中負責維護主題與觀察者映射關係以及在自身狀態改變時通知觀察者的職責從中抽出,放入一個新的角色事件發佈器(EventPublisher)中,事件監聽模式的輪廓就展示在了咱們眼前,以下圖所示
設計模式
常見事件監聽機制的主要角色以下緩存
Spring框架對事件的發佈與監聽提供了相對完整的支持,它擴展了JDK中對自定義事件監聽提供的基礎框架,並與Spring的IOC特性做了整合,使得用戶能夠根據本身的業務特色進行相關的自定義,並依託Spring容器方便的實現監聽器的註冊和事件的發佈。由於Spring的事件監聽依託於JDK提供的底層支持,爲了更好的理解,先來看下JDK中爲用戶實現自定義事件監聽提供的基礎框架。app
JDK爲用戶實現自定義事件監聽提供了兩個基礎的類。一個是表明全部可被監聽事件的事件基類java.util.EventObject,全部自定義事件類型都必須繼承該類,類結構以下所示框架
public class EventObject implements java.io.Serializable { private static final long serialVersionUID = 5516075349620653480L; /** * The object on which the Event initially occurred. */ protected transient Object source; /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @exception IllegalArgumentException if source is null. */ public EventObject(Object source) { if (source == null) throw new IllegalArgumentException("null source"); this.source = source; } /** * The object on which the Event initially occurred. * * @return The object on which the Event initially occurred. */ public Object getSource() { return source; } /** * Returns a String representation of this EventObject. * * @return A a String representation of this EventObject. */ public String toString() { return getClass().getName() + "[source=" + source + "]"; } }
該類內部有一個Object類型的source變量,邏輯上表示發生該事件的事件源,實際中能夠用來存儲包含該事件的一些相關信息。
另外一個則是對全部事件監聽器進行抽象的接口java.util.EventListener,這是一個標記接口,內部沒有任何抽象方法,全部自定義事件監聽器都必須實現該標記接口運維
/** * A tagging interface that all event listener interfaces must extend. * @since JDK1.1 */ public interface EventListener { }
以上就是JDK爲咱們實現自定義事件監聽提供的底層支持。針對具體業務場景,咱們經過擴展java.util.EventObject來自定義事件類型,同時經過擴展java.util.EventListener來定義在特定事件發生時被觸發的事件監聽器。固然,不要忘了還要定義一個事件發佈器來管理事件監聽器並提供發佈事件的功能。異步
想象咱們正在作一個關於Spark的任務調度系統,咱們須要把任務提交到集羣中並監控任務的執行狀態,當任務執行完畢(成功或者失敗),除了必須對數據庫進行更新外,還能夠執行一些額外的工做:好比將任務執行結果以郵件的形式發送給用戶。這些額外的工做後期還有較大的變更可能:好比還須要以短信的形式通知用戶,對於特定的失敗任務須要通知相關運維人員進行排查等等,因此不宜直接寫死在主流程代碼中。最好的方式天然是以事件監聽的方式動態的增刪對於任務執行結果的處理邏輯。爲此咱們能夠基於JDK提供的事件框架,打造一個可以對任務執行結果進行監聽的彈性系統。ide
/** * @author: takumiCX * @create: 2018-11-02 **/ @Data public class Task { private String name; private TaskFinishStatus status; }
任務包含任務名和任務狀態,其中任務狀態是個枚舉常量,只有成功和失敗兩種取值。
/** * @author: takumiCX * @create: 2018-11-02 **/ public enum TaskFinishStatus { SUCCEDD, FAIL; }
/** * @author: takumiCX * @create: 2018-11-02 **/ public class TaskFinishEvent extends EventObject { /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ public TaskFinishEvent(Object source) { super(source); } }
/** * @author: takumiCX * @create: 2018-11-02 **/ public interface TaskFinishEventListner extends EventListener { void onTaskFinish(TaskFinishEvent event); }
/** * @author: takumiCX * @create: 2018-11-03 **/ @Data public class MailTaskFinishListener implements TaskFinishEventListner { private String emial; @Override public void onTaskFinish(TaskFinishEvent event) { System.out.println("Send Emial to "+emial+" Task:"+event.getSource()); } }
/** * @author: takumiCX * @create: 2018-11-03 **/ public class TaskFinishEventPublisher { private List<TaskFinishEventListner> listners=new ArrayList<>(); //註冊監聽器 public synchronized void register(TaskFinishEventListner listner){ if(!listners.contains(listner)){ listners.add(listner); } } //移除監聽器 public synchronized boolean remove(TaskFinishEventListner listner){ return listners.remove(listner); } //發佈任務結束事件 public void publishEvent(TaskFinishEvent event){ for(TaskFinishEventListner listner:listners){ listner.onTaskFinish(event); } } }
/** * @author: takumiCX * @create: 2018-11-03 **/ public class TestTaskFinishListener { public static void main(String[] args) { //事件源 Task source = new Task("用戶統計", TaskFinishStatus.SUCCEDD); //任務結束事件 TaskFinishEvent event = new TaskFinishEvent(source); //郵件服務監聽器 MailTaskFinishListener mailListener = new MailTaskFinishListener("takumiCX@163.com"); //事件發佈器 TaskFinishEventPublisher publisher = new TaskFinishEventPublisher(); //註冊郵件服務監聽器 publisher.register(mailListener); //發佈事件 publisher.publishEvent(event); } }
若是後期由於需求變更須要在任務結束時將結果以短信的方式發送給用戶,則能夠再添加一個短信服務監聽器
/** * @author: takumiCX * @create: 2018-11-03 **/ @Data @AllArgsConstructor public class SmsTaskFinishListener implements TaskFinishEventListner { private String address; @Override public void onTaskFinish(TaskFinishEvent event) { System.out.println("Send Message to "+address+" Task:"+event.getSource()); } }
在測試代碼中添加以下代碼向事件發佈器註冊該監聽器
SmsTaskFinishListener smsListener = new SmsTaskFinishListener("123456789"); //註冊短信服務監聽器 publisher.register(smsListener);
最後運行結果以下
基於JDK的支持要實現對自定義事件的監聽仍是比較麻煩的,要作的工做比較多。並且自定義的事件發佈器也不能提供對全部事件的統一發布支持。基於Spring框架實現自定義事件監聽則要簡單不少,功能也更增強大。
Spring容器,具體而言是ApplicationContext接口定義的容器提供了一套相對完善的事件發佈和監聽框架,其遵循了JDK中的事件監聽標準,並使用容器來管理相關組件,使得用戶不用關心事件發佈和監聽的具體細節,下降了開發難度也簡化了開發流程。下面看看對於事件監聽機制中的各主要角色,Spring框架中是如何定義的,以及相關的類體系結構
事件
Spring爲容器內事件定義了一個抽象類ApplicationEvent,該類繼承了JDK中的事件基類EventObject。於是自定義容器內事件除了須要繼承ApplicationEvent以外,還要傳入事件源做爲構造參數。
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * Handle an application event. * @param event the event to respond to */ void onApplicationEvent(E event); }
1.該接口繼承了JDK中表示事件監聽器的標記接口EventListener,內部只定義了一個抽象方法onApplicationEvent(evnt),當監聽的事件在容器中被髮布,該方法將被調用。
2.同時,該接口是一個泛型接口,其實現類能夠經過傳入泛型參數指定該事件監聽器要對哪些事件進行監聽。這樣有什麼好處?這樣全部的事件監聽器就能夠由一個事件發佈器進行管理,並對全部事件進行統一發布,而具體的事件和事件監聽器之間的映射關係,則能夠經過反射讀取泛型參數類型的方式進行匹配,稍後咱們會對原理進行講解。
3.最後,全部的事件監聽器都必須向容器註冊,容器可以對其進行識別並委託容器內真正的事件發佈器進行管理。
那麼是否能夠說ApplicationContext,即容器自己就擔當了事件發佈器的角色呢?其實這是不許確的,容器自己僅僅是對外提供了事件發佈的接口,真正的工做實際上是委託給了具體容器內部一個ApplicationEventMulticaster
對象,其定義在AbstractApplicationContext抽象類內部,以下所示
/** Helper class used in event publishing */ private ApplicationEventMulticaster applicationEventMulticaster;
因此,真正的事件發佈器是ApplicationEventMulticaster,這是一個接口,定義了事件發佈器須要具有的基本功能:管理事件監聽器以及發佈事件。其默認實現類是
SimpleApplicationEventMulticaster,該組件會在容器啓動時被自動建立,並以單例的形式存在,管理了全部的事件監聽器,並提供針對全部容器內事件的發佈功能。
業務場景在2.1中已經介紹過了,這裏就不在囉嗦。基於Spring框架來實現對自定義事件的監聽流程十分簡單,只須要三部:1.自定義事件類 2.自定義事件監聽器並向容器註冊 3.發佈事件
/** * @author: takumiCX * @create: 2018-11-04 **/ public class TaskFinishEvent2 extends ApplicationEvent { /** * Create a new ApplicationEvent. * * @param source the object on which the event initially occurred (never {@code null}) */ public TaskFinishEvent2(Object source) { super(source); } }
/** * @author: takumiCX * @create: 2018-11-04 **/ @Component public class MailTaskFinishListener2 implements ApplicationListener<TaskFinishEvent2> { private String emial="takumiCX@163.com"; @Override public void onApplicationEvent(TaskFinishEvent2 event) { System.out.println("Send Emial to "+emial+" Task:"+event.getSource()); } }
/** * @author: takumiCX * @create: 2018-11-04 **/ @Component public class EventPublisher implements ApplicationContextAware { private ApplicationContext applicationContext; //發佈事件 public void publishEvent(ApplicationEvent event){ applicationContext.publishEvent(event); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext=applicationContext; } }
在此基礎上,還能夠自定義一個短信服務監聽器,在任務執行結束時發送短信通知用戶。過程和上面自定義郵件服務監聽器相似:實現ApplicationListner接口並重寫抽象方法,而後經過註解或者xml的方式向容器註冊。
Spring事件監聽機制離不開容器IOC特性提供的支持,好比容器會自動建立事件發佈器,自動識別用戶註冊的監聽器並進行管理,在特定的事件發佈後會找到對應的事件監聽器並對其監聽方法進行回調。Spring幫助用戶屏蔽了關於事件監聽機制背後的不少細節,使用戶能夠專一於業務層面進行自定義事件開發。然而咱們仍是忍不住對其背後的實現原理進行一番探討,好比:
爲了對以上問題進行解答,咱們不得不深刻源碼層面一探究竟。
真正的事件發佈器是ApplicationEventMulticaster,它定義在AbstractApplicationContext中,並在ApplicationContext容器啓動的時候進行初始化。在容器啓動的refrsh()方法中能夠找到初始化事件發佈器的入口方法,以下圖所示
protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 判斷beanFactory裏是否認義了id爲applicationEventMulticaster的bean,默認是沒有的 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 { //通常狀況會走這裏,建立一個SimpleApplicationEventMulticaster並交由容器管理 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 + "]"); } } }
這裏會根據核心容器beanFactory中是否有id爲applicationEventMulticaster的bean分兩種狀況:
1.容器中已有id爲applicationEventMulticaster的bean
直接從容器緩存獲取或是建立該bean實例,並交由成員變量applicationEventMulticaster保存。
當用戶自定義了事件發佈器並向容器註冊時會執行該流程。
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { private Executor taskExecutor; private ErrorHandler errorHandler;
public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware { private final ListenerRetriever defaultRetriever = new ListenerRetriever(false); final Map<ListenerCacheKey, ListenerRetriever> retrieverCache = new ConcurrentHashMap<ListenerCacheKey, ListenerRetriever>(64); private ClassLoader beanClassLoader; private BeanFactory beanFactory; private Object retrievalMutex = this.defaultRetriever;
以後會調用beanFactory.registerSingleton方法將建立的SimpleApplicationEventMulticaster實例註冊爲容器的單實例bean。
初始化事件發佈器的工做很是簡單,一句話總結:由容器實例化用戶自定義的事件發佈器或者由容器幫咱們建立一個簡單的事件發佈器並交由容器管理。
註冊事件監聽器的流程在初始化事件發佈器以後,以下圖所示
其關鍵代碼以下所示
// uninitialized to let post-processors apply to them! //獲取實現ApplicationListener接口的全部bean的beanName String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { //將監聽器的beanName保存到事件發佈器中 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); }
首先遍歷beanFactory中全部的bean,獲取全部實現ApplicationListener接口的bean的beanName,並將這些beanName註冊到ApplicationEventMulticaster中
@Override public void addApplicationListenerBean(String listenerBeanName) { synchronized (this.retrievalMutex) { //保存全部監聽器的beanName this.defaultRetriever.applicationListenerBeans.add(listenerBeanName); //清除維護事件和監聽器映射關係的緩存 this.retrieverCache.clear(); } }
defaultRetriever是定義在抽象類AbstractApplicationEventMulticaster中的成員,用來保存全部事件監聽器及其beanName
private final ListenerRetriever defaultRetriever = new ListenerRetriever(false);
其之內部類形式定義在AbstractApplicationEventMulticaster中
/** * Helper class that encapsulates a specific set of target listeners, * allowing for efficient retrieval of pre-filtered listeners. * <p>An instance of this helper gets cached per event type and source type. */ private class ListenerRetriever { //保存全部事件監聽器 public final Set<ApplicationListener<?>> applicationListeners; //保存全部事件監聽器的beanName public final Set<String> applicationListenerBeans;
向事件發佈器註冊監聽器的beanName,其實就是將beanName加入ListenerRetriever的集合中。
其實看到這裏會有一個疑問,registerListeners()方法只是找到了全部監聽器的beanName並將其保存到了事件發佈器ApplicationEventMulticaster中,那麼真正的事件監聽器實例是什麼時候被建立並被加入到事件發佈器中的?
這裏咱們不得不退回到啓動容器的refresh()方法中,在初始化beanFactory以後,初始化事件發佈器以前,容器在prepareBeanFactory(beanFactory)方法中又註冊了一些重要組件,其中就包括一個特殊的BeanPostProcessor:ApplicationListenerDetector,正如其類名暗示的那樣,這是一個事件監聽器的探測器。
該類實現了BeanPostProcessor接口,以下圖所示
ApplicationListenerDetector實現了BeanPostProcessor接口,能夠在容器級別對全部bean的生命週期過程進行加強。這裏主要是爲了可以在初始化全部bean後識別出全部的事件監聽器bean並
將其註冊到事件發佈器中
@Override public Object postProcessAfterInitialization(Object bean, String beanName) { //判斷該bean是否實現了ApplicationListener接口 if (this.applicationContext != null && bean instanceof ApplicationListener) { // potentially not detected as a listener by getBeanNamesForType retrieval Boolean flag = this.singletonNames.get(beanName); if (Boolean.TRUE.equals(flag)) { // singleton bean (top-level or inner): register on the fly //將實現了ApplicationListener接口的bean註冊到事件發佈器applicationEventMulticaster中 this.applicationContext.addApplicationListener((ApplicationListener<?>) bean); } else if (Boolean.FALSE.equals(flag)) { if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) { // inner bean with other scope - can't reliably process events 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."); } this.singletonNames.remove(beanName); } } return bean; }
在初始化全部的bean後,該ApplicationListenerDetector的postProcessAfterInitialization(Object bean, String beanName)方法會被做用在每個bean上,經過判斷傳入的bean
是不是ApplicationListener實例進行過濾,而後將找到的事件監聽器bean註冊到事件發佈器中。
這裏爲了簡化源碼閱讀的工做量,對一些細節和分支情形作了忽略,只考慮主流程,如上圖箭頭所示,這裏調用了事件發佈器的multicastEvent()方法進行事件發佈,須要傳入事件event和事件類型
eventType做爲參數。不過一般這個eventType參數爲null,由於事件的類型信息徹底能夠經過反射的方式從event對象中得到。繼續跟進源碼
@Override public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) { //獲取事件類型 ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); //遍歷全部和事件匹配的事件監聽器 for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) { //獲取事件發佈器內的任務執行器,默認該方法返回null Executor executor = getTaskExecutor(); if (executor != null) { //異步回調監聽方法 executor.execute(new Runnable() { @Override public void run() { invokeListener(listener, event); } }); } else { //同步回調監聽方法 invokeListener(listener, event); } } }
首先經過傳入的參數或者經過調用resolveDefaultEventType(event)方法獲取事件的事件類型信息,以後會經過
getApplicationListeners(event, type)方法獲得全部和該事件類型匹配的事件監聽器,其實現邏輯後面會細說,這裏先跳過。對於匹配的每個監聽器,視事件發佈器內是否設置了
任務執行器實例Executor,決定以何種方式對監聽器的監聽方法進行回調。
好了,如今能夠來探究下困擾咱們好久的一個問題了,那就是:如何根據事件類型找到匹配的全部事件監聽器?這部分邏輯在getApplicationListeners方法中
protected Collection<ApplicationListener<?>> getApplicationListeners( ApplicationEvent event, ResolvableType eventType) { //獲取事件中的事件源對象 Object source = event.getSource(); //獲取事件源類型 Class<?> sourceType = (source != null ? source.getClass() : null); //以事件類型和事件源類型爲參數構建一個cacheKey,用於從緩存map中獲取與之匹配的監聽器列表 ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType); // Quick check for existing entry on ConcurrentHashMap... ListenerRetriever retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { //從緩存中獲取監聽器列表 return retriever.getApplicationListeners(); } if (this.beanClassLoader == null || (ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) && (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) { // Fully synchronized building and caching of a ListenerRetriever synchronized (this.retrievalMutex) { retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { return retriever.getApplicationListeners(); } retriever = new ListenerRetriever(true); //查找全部與發佈事件匹配的監聽器列表 Collection<ApplicationListener<?>> listeners = retrieveApplicationListeners(eventType, sourceType, retriever); //將匹配結果緩存到map中 this.retrieverCache.put(cacheKey, retriever); return listeners; } } else { // No ListenerRetriever caching -> no synchronization necessary return retrieveApplicationListeners(eventType, sourceType, null); } }
整個流程能夠歸納爲:
final Map<ListenerCacheKey, ListenerRetriever> retrieverCache = new ConcurrentHashMap<ListenerCacheKey, ListenerRetriever>(64);
ListenerCacheKey由事件類型eventType和事件源類型sourceType構成,ListenerRetriever內部則維護了一個監聽器列表。當所發佈的事件類型和事件源類型與Map中的key匹配時,
將直接返回value中的監聽器列表做爲匹配結果,一般這發生在事件不是第一次發佈時,能避免遍歷全部監聽器並進行過濾,若是事件時第一次發佈,則會執行流程2。
Collection<ApplicationListener<?>> listeners = retrieveApplicationListeners(eventType, sourceType, retriever);
/** * Actually retrieve the application listeners for the given event and source type. * @param eventType the event type * @param sourceType the event source type * @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes) * @return the pre-filtered list of application listeners for the given event and source type */ private Collection<ApplicationListener<?>> retrieveApplicationListeners( ResolvableType eventType, Class<?> sourceType, ListenerRetriever retriever) { //這是存放匹配的監聽器的列表 LinkedList<ApplicationListener<?>> allListeners = new LinkedList<ApplicationListener<?>>(); Set<ApplicationListener<?>> listeners; Set<String> listenerBeans; synchronized (this.retrievalMutex) { listeners = new LinkedHashSet<ApplicationListener<?>>(this.defaultRetriever.applicationListeners); listenerBeans = new LinkedHashSet<String>(this.defaultRetriever.applicationListenerBeans); } //遍歷全部的監聽器 for (ApplicationListener<?> listener : listeners) { //判斷該事件監聽器是否匹配 if (supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListeners.add(listener); } //將匹配的監聽器加入列表 allListeners.add(listener); } } //這部分能夠跳過 if (!listenerBeans.isEmpty()) { BeanFactory beanFactory = getBeanFactory(); for (String listenerBeanName : listenerBeans) { try { Class<?> listenerType = beanFactory.getType(listenerBeanName); if (listenerType == null || supportsEvent(listenerType, eventType)) { ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class); if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListenerBeans.add(listenerBeanName); } allListeners.add(listener); } } } catch (NoSuchBeanDefinitionException ex) { // Singleton listener instance (without backing bean definition) disappeared - // probably in the middle of the destruction phase } } } //對匹配的監聽器列表進行排序 AnnotationAwareOrderComparator.sort(allListeners); return allListeners; }
判斷監聽器是否匹配的邏輯在supportsEvent(listener, eventType, sourceType)中,
protected boolean supportsEvent(ApplicationListener<?> listener, ResolvableType eventType, Class<?> sourceType) { //對原始的ApplicationListener進行一層適配器包裝成爲GenericApplicationListener GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ? (GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener)); //判斷監聽器是否支持該事件類型以及該事件源類型 return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType)); }
首先對原始的ApplicationListener進行一層適配器包裝成GenericApplicationListener,便於後面使用該接口中定義的方法判斷監聽器是否支持傳入的事件類型或事件源類型
public interface GenericApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered { /** * Determine whether this listener actually supports the given event type. */ boolean supportsEventType(ResolvableType eventType); //判斷是否支持該事件類型 /** * Determine whether this listener actually supports the given source type. */ boolean supportsSourceType(Class<?> sourceType); //判斷是否支持該事件源類型 }
smartListener.supportsEventType(eventType)用來判斷監聽器是否支持該事件類型,由於咱們的監聽器實例一般都不是SmartApplicationListener類型,因此直接看下面箭頭所指的方法就好
declaredEventType是監聽器泛型的實際類型,而eventType是發佈的事件的類型
declaredEventType.isAssignableFrom(eventType)當如下兩種狀況返回true
而對於事件源類型而言,一般默認會直接返回true,也就是說事件源的類型一般對於判斷匹配的監聽器沒有意義。
這裏查找到全部匹配的監聽器返回後會將匹配關係緩存到retrieverCache這個map中
Collection<ApplicationListener<?>> listeners = retrieveApplicationListeners(eventType, sourceType, retriever); //將匹配結果緩存到map中 this.retrieverCache.put(cacheKey, retriever); return listeners;
梳理下容器事件發佈的整個流程,能夠總結以下
這篇文章主要是爲了梳理下Spring的容器內事件體系並對其工做原理作必定程度上的源碼上的剖析,原本還想展現一些關於Spring事件發佈監聽機制的一些擴展特性和額外功能,不過因爲前面廢話太多致使篇幅 已經大大超出了預期,後面這部分只能有時間另開一篇再說了。