public ConfigurableApplicationContext run(String... args) { ......//省略 // 獲取一個run監聽器,主要監聽SpringApplication對象,(內部只有一個EventPublishingRunListener) SpringApplicationRunListeners listeners = getRunListeners(args); //調用監聽器的啓動,當SpringApplication對象的run方法剛啓動的時候(依靠SimpleApplicationEventMulticaster) listeners.starting(); ......//省略 }
SpringApplicationRunListeners 是一個集合類,內部包含一個 log 和包含 SpringApplicationRunListener 的 List。而 SpringApplicationRunListener 主要是監聽 SpringApplication 對象的,裏面的方法都定義了在什麼時候調用 SpringApplicationRunListener 的各類方法。java
下面的每個方法 SpringApplicationRunListener 都把其包裝成一個事件,在spring容器還未成功 refreshed 以前都是使用SimpleApplicationEventMulticaster 去尋找對該事件感興趣的ApplicationListener,而後調用其onApplicationEvent方法spring
public class SpringApplication { // 獲取監聽 private SpringApplicationRunListeners getRunListeners(String[] args) { // 定義class數組 Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class }; // 建立SpringApplicationRunListeners對象 return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances( SpringApplicationRunListener.class, types, this, args)); } }
默認狀況下,getRunListeners 方法從 spring.factories 文件中找出key爲 SpringApplicationRunListener 的類有:數組
org.springframework.boot.context.event.EventPublishingRunListenerapp
這裏咱們看到了一個熟悉的方法getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),前面的博文咱們已經詳細介紹過該方法是怎麼一步步的獲取到META-INF/spring.factories中的指定的key的value,獲取到之後怎麼實例化類的(參考)。執行 獲取的值以下圖源碼分析
從上圖debug結果,咱們能夠看到咱們獲取到了一個監聽器EventPublishingRunListener,該監聽器是Spring容器的啓動監聽器。listeners.starting()方法開啓了監聽事件ui
public class EventPublishingRunListener implements SpringApplicationRunListener, Ordered { private final SpringApplication application; private final String[] args; private final SimpleApplicationEventMulticaster initialMulticaster; // 加載監聽器類 public EventPublishingRunListener(SpringApplication application, String[] args) { this.application = application; this.args = args; this.initialMulticaster = new SimpleApplicationEventMulticaster(); // 給initialMulticaster 添加listener for (ApplicationListener<?> listener : application.getListeners()) { this.initialMulticaster.addApplicationListener(listener); } } // 實現類調用EventPublishingRunListener的方法 public void starting() { this.initialMulticaster.multicastEvent( // 建立了一個ApplicationStartingEvent事件,將springapplication的this.application傳入,所以監聽的時候獲取的是SpringApplication實例 new ApplicationStartingEvent(this.application, this.args)); } ......//省略 }
EventPublishingRunListener的初始化方法中 對application、args進行了賦值,並對SimpleApplicationEventMulticaster進行了初始化,而後獲取application中的監聽器添加給SimpleApplicationEventMulticaster對象。this
進入SimpleApplicationEventMulticaster類的初始化方法,以下spa
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { private Executor taskExecutor; private ErrorHandler errorHandler; public void multicastEvent(ApplicationEvent event) { multicastEvent(event, resolveDefaultEventType(event)); } public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); // 注意getApplicationListeners獲取對應的事件監聽器 for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) { Executor executor = getTaskExecutor(); if (executor != null) { executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } } } }
SimpleApplicationEventMulticaster類繼承 AbstractApplicationEventMulticaster.net
public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware { protected Collection<ApplicationListener<?>> getApplicationListeners( ApplicationEvent event, ResolvableType eventType) { Object source = event.getSource(); Class<?> sourceType = (source != null ? source.getClass() : null); ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType); // Quick check for existing entry on ConcurrentHashMap… // 快速檢測 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); this.retrieverCache.put(cacheKey, retriever); return listeners; } } else { // No ListenerRetriever caching -> no synchronization necessary return retrieveApplicationListeners(eventType, sourceType, null); } } // 實際上檢索給定事件和源類型的應用程序監聽器是否匹配 private Collection<ApplicationListener<?>> retrieveApplicationListeners( ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable ListenerRetriever retriever) { List<ApplicationListener<?>> allListeners = new ArrayList<>(); Set<ApplicationListener<?>> listeners; Set<String> listenerBeans; synchronized (this.retrievalMutex) { // 這個listener集合就是前文提到的從配置中過濾的10個監聽器(圖1) listeners = new LinkedHashSet<>(this.defaultRetriever.applicationListeners); listenerBeans = new LinkedHashSet<>(this.defaultRetriever.applicationListenerBeans); } // 循環10個listener調用supportsEvent方法 for (ApplicationListener<?> listener : listeners) { if (supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListeners.add(listener); } allListeners.add(listener); } } ......//省略 AnnotationAwareOrderComparator.sort(allListeners); if (retriever != null && retriever.applicationListenerBeans.isEmpty()) { retriever.applicationListeners.clear(); retriever.applicationListeners.addAll(allListeners); } return allListeners; } protected boolean supportsEvent( ApplicationListener<?> listener, ResolvableType eventType, @Nullable Class<?> sourceType) { GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ? (GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener)); return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType)); } }
-->程序啓動
-->調用getRunListeners(args)獲取SpringApplicationRunListeners實例
-->getSpringFactoriesInstances()獲取Spring工廠實例集合
-->loadFactoryNames()經過classLoader加載/META-INF/spring.factories文件,獲取指定class對應的類全限定名稱集合
-->loadSpringFactories() 經過classLoader循環加載/META-INF/spring.factories文件,獲取文件中類全限定名稱集合返回
-->createSpringFactoriesInstances()根據加載文件返回的類全限定名稱集合建立工廠實例,反射
-->listeners.starting()啓動監聽器
-->multicastEvent(ApplicationEvent event)組播ApplicationEvent事件
-->getApplicationListeners()判斷監聽器類型是否與當前監聽器類型相同
-->retrieveApplicationListeners(eventType, sourceType, retriever)檢索給定事件和源類型的應用程序監聽器。
-->supportsEvent(listener, eventType, sourceType)確認給定的監聽器是否支持給定的事件。
-->GenericApplicationListenerAdapter(ApplicationListener<?> delegate)爲給定的委託建立一個新的GenericApplicationListener。
-->resolveDeclaredEventType(ApplicationListener<ApplicationEvent> listener)發佈事件監聽
-->supportsEventType(eventType)從指定類型解析事件
-->結束debug