springboot啓動流程(二)SpringApplication run方法核心邏輯

全部文章

http://www.javashuo.com/article/p-uvudtich-bm.htmlhtml

 

run方法邏輯

上一篇文章中,咱們看到SpringApplication的靜態方法最終是去構造了一個SpringApplication實例對象,並調用了SpringApplication的成員方法runspring

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    return new SpringApplication(primarySources).run(args);
}

本文將梳理一下run方法的代碼主要的邏輯,爲後面其它內容作一個鋪墊app

 

跟進run方法,這個方法的代碼有點長咱們將拋棄掉一些比較次要的內容spa

public ConfigurableApplicationContext run(String... args) {
    // 聲明一個Context容器
    ConfigurableApplicationContext context = null;
    // 獲取監聽器
    SpringApplicationRunListeners listeners = getRunListeners(args);
    // 調用監聽器的啓動
    listeners.starting();

    try {
        // 建立並配置Environment(這個過程會加載application配置文件)
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        // 根據應用類型建立對應的Context容器
        context = createApplicationContext();

        // 刷新Context容器以前的準備
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        // 刷新Context容器
        refreshContext(context);
        // 刷新Context容器以後處理
        afterRefresh(context, applicationArguments);

        // Context容器refresh完畢發佈
        listeners.started(context);

        // 觸發Context容器refresh完之後的執行
        callRunners(context, applicationArguments);
    } catch (Throwable ex) {}

    try {
        // Context啓動完畢,Runner運行完畢發佈
        listeners.running(context);
    } catch (Throwable ex) {}

    return context;
}

簡化後的代碼看起來就比較清晰了,咱們再整理一下邏輯code

1)首先會從spring.factories配置文件中獲取SpringApplicationRunListener監聽器並啓動監聽器;htm

2)然後就會去建立Environment對象

3)緊接着建立ApplicationContextblog

4)ApplicationContext的refresh的事前準備事件

5)ApplicationContext的refreshget

6)ApplicationContext的refresh以後

7)發佈ApplicationContext的refresh完畢的事件

8)觸發runner

9)最後發佈refresh完畢、runner執行完畢的事件

run方法描述了SpringApplication這個類的職責,包含了很多步驟,但簡單的看其實就是爲了建立並配置好一個ApplicationContext。

 

總結

咱們忽略各類細節之後就會發現,SpringApplication的run方法主要就是爲了構建出一個ApplicationContext,後續文章也將圍繞着構建ApplicationContext相關的內容展開。

相關文章
相關標籤/搜索