前言
Springboot啟動源碼系列還只寫了一篇,已經過去一周,又到了每周一更的時間了(是不是很熟悉?),大家有沒有很期待了?我會盡量保證啟動源碼系列每周一更,爭取不讓大家每周的期望落空。一周之中可能會插入其他內容的博文,可能和springboot啟動源碼有關,也可能和啟動源碼無關。
路漫漫其修遠兮,吾將上下而求索!
github:https://github.com/youzhibing
碼雲(gitee):https://gitee.com/youzhibing
前情回顧
這篇是在設計模式之觀察者模式,事件機制的底層原理和spring-boot-2.0.3啟動源碼篇一 - SpringApplication構造方法這兩篇的基礎上進行的,沒看的小伙伴可以先去看看這兩篇。如果大家不想去看,這里我幫大家簡單回顧下。
SpringApplication的構造方法主要做了以下3件事:
1、推測web應用類型,並賦值到屬性webApplicationType
2、設置屬性List<ApplicationContextInitializer<?>> initializers和List<ApplicationListener<?>> listeners
中途讀取了類路徑下所有META-INF/spring.factories的屬性,並緩存到了SpringFactoriesLoader的cache緩存中,而這個cache會在本文中用到
3、 推斷主類,並賦值到屬性mainApplicationClass
spring-boot-2.0.3啟動源碼篇一 - SpringApplication構造方法
事件機制是基於觀察者模式實現的。主要包括幾下4個角色:
事件源:觸發事件的主體
事件:事件本身,指的是EventObject中的source,具體可以是任何數據(包括事件源),用來傳遞數據
事件監聽器:當事件發生時,負責對事件的處理
事件環境:整個事件所處的上下文,對整個事件提供支持
SpringApplicationRunListener
run方法的源代碼如下

/** * Run the Spring application, creating and refreshing a new * {@link ApplicationContext}. * @param args the application arguments (usually passed from a Java main method) * @return a running {@link ApplicationContext} */ public ConfigurableApplicationContext run(String... args) { // 秒表,用於記錄啟動時間;記錄每個任務的時間,最后會輸出每個任務的總費時 StopWatch stopWatch = new StopWatch(); stopWatch.start(); // spring應用上下文,也就是我們所說的spring根容器 ConfigurableApplicationContext context = null; // 自定義SpringApplication啟動錯誤的回調接口 Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); // 設置jdk系統屬性java.awt.headless,默認情況為true即開啟;更多java.awt.headless信息大家可以去查閱資料,這不是本文重點 configureHeadlessProperty(); // 獲取啟動時監聽器 SpringApplicationRunListeners listeners = getRunListeners(args) // 觸發啟動事件,相應的監聽器會被調用,這是本文重點 listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); configureIgnoreBeanInfo(environment); Banner printedBanner = printBanner(environment); context = createApplicationContext(); exceptionReporters = getSpringFactoriesInstances( SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); prepareContext(context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } listeners.started(context); callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try { listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context; }
再講今天的主角之前,我們先來看看ConfigurableApplicationContext,從名字來看就是:配置應用上下文,會根據class路徑下的類初始化配置合適的應用上下文,比如是普通的spring應用(非web應用),還是web應用上下文。類圖和類繼承圖如下
ConfigurableApplicationContext類圖
ConfigurableApplicationContext類繼承圖
ConfigurableApplicationContext不會在本文詳解,他的創建會在后續的博文中講到,這里只是一個提醒。今天的主角是以下兩行代碼
SpringApplicationRunListeners listeners = getRunListeners(args)
listeners.starting();
我們今天的目的就是看看這兩行代碼到底做了些什么
getRunListeners
我們先看看SpringApplicationRunListeners和SpringApplicationRunListener。
SpringApplicationRunListeners的類注釋很簡單:
一個存SpringApplicationRunListener的集合,里面有些方法,后續都會講到;
SpringApplicationRunListener的接口注釋也簡單:
監聽SpringApplication的run方法。通過SpringFactoriesLoader加載SpringApplicationRunListener(一個或多個),SpringApplicationRunListener的實現類必須聲明一個接收SpringApplication實例和String[]數組的公有構造方法。
接下來我們看看getRunListeners方法,源代碼如下
private SpringApplicationRunListeners getRunListeners(String[] args) { Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class }; return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances( SpringApplicationRunListener.class, types, this, args)); }
初略來看的話,就是返回一個新的SpringApplicationRunListeners實例對象;
細看的話,發現有個getSpringFactoriesInstances方法的調用,這個方法大家還記得嗎?(詳情請看spring-boot-2.0.3啟動源碼篇一 - SpringApplication構造方法)getSpringFactoriesInstances在SpringApplication的構造方法中調用了兩次,分別用來設置屬性List<ApplicationContextInitializer<?>> initializers和List<ApplicationListener<?>> listeners。getSpringFactoriesInstances在第一次被調用時會將類路徑下所有的META-INF/spring.factories的文件中的屬性進行加載並緩存到SpringFactoriesLoader的緩存cache中,下次被調用的時候就直接從SpringFactoriesLoader的cache中取數據了。這次就是從SpringFactoriesLoader的cache中取SpringApplicationRunListener類型的類(全限定名),然后實例化后返回。我們來跟下這次getSpringFactoriesInstances獲取的的內容
EventPublishingRunListener的構造方法中,構造了一個SimpleApplicationEventMulticaster對象,並將SpringApplication的listeners中的全部listener賦值到SimpleApplicationEventMulticaster對象的屬性defaultRetriever(類型是ListenerRetriever)的applicationListeners集合中,如下圖
總的來說,getRunListeners做了什么事呢?就是獲取SpringApplicationRunListener類型的實例(EventPublishingRunListener對象),並封裝進SpringApplicationRunListeners對象,然后返回這個SpringApplicationRunListeners對象。說的再簡單點,getRunListeners就是准備好了運行時監聽器EventPublishingRunListener。
listeners.starting()
我們看看starting方法做了些什么事
構建了一個ApplicationStartingEvent事件,並將其發布出去,其中調用了resolveDefaultEventType方法,該方法返回了一個封裝了事件的默認類型(ApplicationStartingEvent)的ResolvableType對象。我們接着往下看,看看這個發布過程做了些什么
multicastEvent
源代碼如下
@Override public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) { Executor executor = getTaskExecutor(); if (executor != null) { executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } } }
初略的看,就是遍歷getApplicationListeners(event, type),然后對每個listener進行invokeListener(listener, event)
getApplicationListeners
根據其注釋可知,該方法作用:返回與給定事件類型匹配的ApplicationListeners集合,非匹配的偵聽器會被提前排除;允許根據緩存的匹配結果來返回。
從上圖可知,主要涉及到3個點:緩存retrieverCache、retrieveApplicationListeners已經retrieveApplicationListeners中調用的supportsEvent方法。流程是這樣的:
1、緩存中是否有匹配的結果,有則返回
2、若緩存中沒有匹配的結果,則從this.defaultRetriever.applicationListeners中過濾,這個this表示的EventPublishingRunListener對象的屬性initialMulticaster(也就是SimpleApplicationEventMulticaster對象,而defaultRetriever.applicationListeners的值也是在EventPublishingRunListener構造方法中初始化的)
3、過濾過程,遍歷defaultRetriever.applicationListeners集合,從中找出ApplicationStartingEvent匹配的listener,具體的匹配規則需要看各個listener的supportsEventType方法(有兩個重載的方法)
4、將過濾的結果緩存到retrieverCache
5、將過濾出的結果返回回去
我們看看,過濾出的listener對象有哪些
invokeListener
其注釋:使用給定的事件調用給定的監聽器
getApplicationListeners方法過濾出的監聽器都會被調用,過濾出來的監聽器包括LoggingApplicationListener、BackgroundPreinitializer、DelegatingApplicationListener、LiquibaseServiceLocatorApplicationListener、EnableEncryptablePropertiesBeanFactoryPostProcessor五種類型的對象。這五個對象的onApplicationEvent都會被調用。
那么這五個監聽器的onApplicationEvent都做了些什么了,我這里大概說下,細節的話大家自行去跟源碼
LoggingApplicationListener:檢測正在使用的日志系統,默認是logback,支持3種,優先級從高到低:logback > log4j > javalog。此時日志系統還沒有初始化
BackgroundPreinitializer:另起一個線程實例化Initializer並調用其run方法,包括驗證器、消息轉換器等等
DelegatingApplicationListener:此時什么也沒做
LiquibaseServiceLocatorApplicationListener:此時什么也沒做
EnableEncryptablePropertiesBeanFactoryPostProcessor:此時僅僅打印了一句日志,其他什么也沒做
總結
事件機制要素
這里和大家一起把事件4要素找出來
事件源:SpringApplication
事件:ApplicationStartingEvent
監聽器:過濾后的監聽器,具體5個上文中已經說過
事件環境:EventPublishingListener,提供環境支持事件,並且發布事件(starting方法)
監聽器數量
項目中集成的功能的多少的不同,從spring.factories加載的屬性數量也不同,自然監聽器數量也會有所不同;如果大家看源碼的時候發現比我的多或者少,不要驚慌,這是很正常的,因為我們集成的功能有所差別。
友情提醒
博文中有些地方分析的不是特別細,需要大家自行去跟源碼,沒涉及到復雜的模式,相信大家也都能看懂。過濾監聽器的時候用到了supportsEvent方法,這個方法里面涉及到了適配器模式,改天我結合session共享給大家分析下適配器模式。
高光時刻
有時候,不是對手有多強大,只是我們不敢去嘗試;勇敢踏出第一步,你會發現自己比想象中更優秀!誠如海因斯第一次跑進人類10s大關時所說:上帝啊,原來那扇門是虛掩着的!
參考
springboot源碼