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


所有文章

https://www.cnblogs.com/lay2017/p/11478237.html

 

run方法邏輯

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

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

本文將梳理一下run方法的代碼主要的邏輯,為后面其它內容做一個鋪墊

 

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

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

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

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

2)而后就會去創建Environment

3)緊接着創建ApplicationContext

4)ApplicationContext的refresh的事前准備

5)ApplicationContext的refresh

6)ApplicationContext的refresh之后

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

8)觸發runner

9)最后發布refresh完畢、runner執行完畢的事件

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

 

總結

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM