09.10 spring-boot-2.0.3不一樣系列之源碼篇

- SpringApplication的run方法(一)之SpringApplicationRunListener,絕對有值得你看的地方

前言

Springboot啟動源碼系列還只寫了一篇,已經過去一週,又到了每週一更的時間了(是不是很熟悉?),大家有沒有很期待了?我會盡量保證啟動源碼系列每週一更,爭取不讓大家每週的期望落空。一週之中可能會插入其他內容的博文,可能和springboot啟動源碼有關,也可能和啟動源碼無關。

路漫漫其修遠兮,吾將上下而求索!

github:https://github.com/youzhibing

碼雲(gitee):https://gitee.com/youzhibing

前情回顧

這篇是在spring-boot-2.0.3不一樣系列之源碼篇 - springboot源碼一,絕對有值得你看的地方和spring-boot-2.0.3不一樣系列之番外篇 - springboot事件機制,絕對有值得你看的地方這兩篇的基礎上進行的,沒看的小夥伴可以先去看看這兩篇。如果大家不想去看,這裡我幫大家簡單回顧下。

spring-boot-2.0.3不一樣系列之源碼篇 - springboot源碼一,絕對有值得你看的地方

SpringApplication的構造方法主要做了以下3件事:

1、推測web應用類型,並賦值到屬性webApplicationType

2、設置屬性List<applicationcontextinitializer>> initializers和List<applicationlistener>> listeners/<applicationlistener>/<applicationcontextinitializer>

中途讀取了類路徑下所有META-INF/spring.factories的屬性,並緩存到了SpringFactoriesLoader的cache緩存中,而這個cache會在本文中用到

3、 推斷主類,並賦值到屬性mainApplicationClass

spring-boot-2.0.3不一樣系列之番外篇 - springboot事件機制,絕對有值得你看的地方

事件機制是基於觀察者模式實現的。主要包括幾下4個角色:

事件源:觸發事件的主體

事件:事件本身,指的是EventObject中的source,具體可以是任何數據(包括事件源),用來傳遞數據

事件監聽器:當事件發生時,負責對事件的處理

事件環境:整個事件所處的上下文,對整個事件提供支持

SpringApplicationRunListener

run方法的源代碼如下

spring-boot-2.0.3不一樣系列之源碼篇

View Code

再講今天的主角之前,我們先來看看ConfigurableApplicationContext,從名字來看就是:配置應用上下文,會根據class路徑下的類初始化配置合適的應用上下文,比如是普通的spring應用(非web應用),還是web應用上下文。類圖和類繼承圖如下

ConfigurableApplicationContext類圖

spring-boot-2.0.3不一樣系列之源碼篇

ConfigurableApplicationContext類繼承圖

spring-boot-2.0.3不一樣系列之源碼篇

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不一樣系列之源碼篇 - springboot源碼一,絕對有值得你看的地方)getSpringFactoriesInstances在SpringApplication的構造方法中調用了兩次,分別用來設置屬性List<applicationcontextinitializer>> initializers和List<applicationlistener>> listeners。getSpringFactoriesInstances在第一次被調用時會將類路徑下所有的META-INF/spring.factories的文件中的屬性進行加載並緩存到SpringFactoriesLoader的緩存cache中,下次被調用的時候就直接從SpringFactoriesLoader的cache中取數據了。這次就是從SpringFactoriesLoader的cache中取SpringApplicationRunListener類型的類(全限定名),然後實例化後返回。我們來跟下這次getSpringFactoriesInstances獲取的的內容/<applicationlistener>/<applicationcontextinitializer>

spring-boot-2.0.3不一樣系列之源碼篇

EventPublishingRunListener的構造方法中,構造了一個SimpleApplicationEventMulticaster對象,並將SpringApplication的listeners中的全部listener賦值到SimpleApplicationEventMulticaster對象的屬性defaultRetriever(類型是ListenerRetriever)的applicationListeners集合中,如下圖

spring-boot-2.0.3不一樣系列之源碼篇

總的來說,getRunListeners做了什麼事呢?就是獲取SpringApplicationRunListener類型的實例(EventPublishingRunListener對象),並封裝進SpringApplicationRunListeners對象,然後返回這個SpringApplicationRunListeners對象。說的再簡單點,getRunListeners就是準備好了運行時監聽器EventPublishingRunListener。

listeners.starting()

我們看看starting方法做了些什麼事

spring-boot-2.0.3不一樣系列之源碼篇

構建了一個ApplicationStartingEvent事件,並將其發佈出去,其中調用了resolveDefaultEventType方法,該方法返回了一個封裝了事件的默認類型(ApplicationStartingEvent)的ResolvableType對象。我們接著往下看,看看這個發佈過程做了些什麼

multicastEvent

源代碼如下

spring-boot-2.0.3不一樣系列之源碼篇

@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);
}
}
}

spring-boot-2.0.3不一樣系列之源碼篇

初略的看,就是遍歷getApplicationListeners(event, type),然後對每個listener進行invokeListener(listener, event)

getApplicationListeners

根據其註釋可知,該方法作用:返回與給定事件類型匹配的ApplicationListeners集合,非匹配的偵聽器會被提前排除;允許根據緩存的匹配結果來返回。

spring-boot-2.0.3不一樣系列之源碼篇

從上圖可知,主要涉及到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對象有哪些

spring-boot-2.0.3不一樣系列之源碼篇

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源碼


分享到:


相關文章: