spring-boot-2.0.3啓動源碼篇二 - run方法(一)之SpringApplicationRunListener

前言

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

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

  github:https://github.com/youzhibinggit

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

前情回顧

  這篇是在設計模式之觀察者模式,事件機制的底層原理spring-boot-2.0.3啓動源碼篇一 - SpringApplication構造方法這兩篇的基礎上進行的,沒看的小夥伴能夠先去看看這兩篇。若是你們不想去看,這裏我幫你們簡單回顧下。web

  設計模式之觀察者模式,事件機制的底層原理spring

    SpringApplication的構造方法主要作了如下3件事:設計模式

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

      二、設置屬性List<ApplicationContextInitializer<?>> initializers和List<ApplicationListener<?>> listeners緩存

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

      三、 推斷主類,並賦值到屬性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;
}
View Code

  再講今天的主角以前,咱們先來看看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方法。流程是這樣的:

      一、緩存中是否有匹配的結果,有則返回

      二、若緩存中沒有匹配的結果,則從this.defaultRetriever.applicationListeners中過濾,這個this表示的EventPublishingRunListener對象的屬性initialMulticaster(也就是SimpleApplicationEventMulticaster對象,而defaultRetriever.applicationListeners的值也是在EventPublishingRunListener構造方法中初始化的

      三、過濾過程,遍歷defaultRetriever.applicationListeners集合,從中找出ApplicationStartingEvent匹配的listener,具體的匹配規則須要看各個listener的supportsEventType方法(有兩個重載的方法)

      四、將過濾的結果緩存到retrieverCache

      五、將過濾出的結果返回回去

    咱們看看,過濾出的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源碼

相關文章
相關標籤/搜索