SpringApplication到底run了什麼(上)

来源:https://www.cnblogs.com/zhixiang-org-cn/archive/2019/09/23/11575705.html
-Advertisement-
Play Games

在上篇文章: "SpringBoot源碼解析:創建SpringApplication對象實例" 中,我們詳細描述了SpringApplication對象實例的創建過程,本篇文章繼續看 方法的執行邏輯吧 1. 第一行使用了 來記錄開始時間 2. 設置了 環境變數,在網上瞭解了一下這個變數的相關信息 H ...


在上篇文章:SpringBoot源碼解析:創建SpringApplication對象實例中,我們詳細描述了SpringApplication對象實例的創建過程,本篇文章繼續看run方法的執行邏輯吧

    public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting();
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                    args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners,
                    applicationArguments);
            //後面還有,本篇文章就解析到這。。。。
    }
  1. 第一行使用了StopWatch來記錄開始時間
  2. 設置了java.awt.headless環境變數,在網上瞭解了一下這個變數的相關信息

    Headless模式是系統的一種配置模式。在系統可能缺少顯示設備、鍵盤或滑鼠這些外設的情況下可以使用該模式

    個人理解為是一些圖形相關的組件能否使用的開關,歡迎各位大佬指正

  3. 接著遍歷所有構造SpringApplication實例時載入的SpringApplicationRunListener,調用它們的started方法

這裡構造時僅僅載入了一個EventPublishingRunListener類,所以咱們就來解析一下這個東東

    public void starting() {
        this.initialMulticaster.multicastEvent(
                new ApplicationStartingEvent(this.application, this.args));
    }

可以看到這裡調用了SimpleApplicationEventMulticaster類的multicastEvent方法並且傳入了ApplicationStartingEvent對象,看名字就知道了這個是SpringBoot啟動事件


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方法,這個方法中主要就是從最啟動時獲取的所有監聽器和這個事件做了下匹配,返回通過匹配的監聽器集合

接著就是看是否設置線程池參數,如果有線程池則使用線程池的線程進行操作,否則將同步調用監聽器

  1. 把所有的命令行啟動參數封裝成ConfigurableEnvironment對象
  2. 準備運行時環境
    private ConfigurableEnvironment prepareEnvironment(
            SpringApplicationRunListeners listeners,
            ApplicationArguments applicationArguments) {
        ConfigurableEnvironment environment = getOrCreateEnvironment();
        configureEnvironment(environment, applicationArguments.getSourceArgs());
        listeners.environmentPrepared(environment);
        if (!this.webEnvironment) {
            environment = new EnvironmentConverter(getClassLoader())
                    .convertToStandardEnvironmentIfNecessary(environment);
        }
        return environment;
    }
獲取或創建環境getOrCreateEnvironment

方法名就很直觀,有就直接獲取,沒有就新建

    private ConfigurableEnvironment getOrCreateEnvironment() {
        if (this.environment != null) {
            return this.environment;
        }
        if (this.webApplicationType == WebApplicationType.SERVLET) {
            return new StandardServletEnvironment();
        }
        return new StandardEnvironment();
    }

上篇文章中說過了,咱們是Servlet環境,所以當前方法是返回一個StandardServletEnvironment對象,這個對象的構造過程中調用了customizePropertySources方法(它父類的父類調用的)

    protected void customizePropertySources(MutablePropertySources propertySources) {
        propertySources.addLast(new StubPropertySource("servletConfigInitParams"));
        propertySources.addLast(new StubPropertySource("servletContextInitParams"));
        if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
            propertySources.addLast(new JndiPropertySource("jndiProperties"));
        }
        super.customizePropertySources(propertySources);
    }
  //這是它父類的
 protected void customizePropertySources(MutablePropertySources propertySources) {
        propertySources.addLast(new MapPropertySource("systemProperties", getSystemProperties()));
        propertySources.addLast(new SystemEnvironmentPropertySource("systemEnvironment", getSystemEnvironment()));
    }

可以看出StandardServletEnvironmentpropertySources中添加了兩個StubPropertySource對象,而它的父類添加了一個包含java系統屬性和一個操作系統環境變數的對象

配置 configureEnvironment

protected void configureEnvironment(ConfigurableEnvironment environment,
    String[] args) {
    // 配置PropertySources
    configurePropertySources(environment, args);
    // 配置Profiles
    configureProfiles(environment, args);
}

分別看一下兩個方法

配置PropertySources
protected void configurePropertySources(ConfigurableEnvironment environment,
        String[] args) {
    MutablePropertySources sources = environment.getPropertySources();
    if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
        // 存在預設配置將其放到最後位置
        sources.addLast(
                new MapPropertySource("defaultProperties", this.defaultProperties));
    }
    // 如果存在命令行參數則將原有的替換掉
    if (this.addCommandLineProperties && args.length > 0) {
        String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
        if (sources.contains(name)) {
            PropertySource<?> source = sources.get(name);
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(new SimpleCommandLinePropertySource(
                    "springApplicationCommandLineArgs", args));
            composite.addPropertySource(source);
            sources.replace(name, composite);
        }
        else {
            // 將其放到第一位置
            sources.addFirst(new SimpleCommandLinePropertySource(args));
        }
    }
}

這裡就體現出了這個命令行參數比應用配置文件的優先順序高的情況了

配置Profiles

從PropertySources中查找spring.profiles.active屬性,存在則將其值添加activeProfiles集合中

protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
    environment.getActiveProfiles(); 
    Set<String> profiles = new LinkedHashSet<>(this.additionalProfiles);
    profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
    environment.setActiveProfiles(StringUtils.toStringArray(profiles));
}
發佈EnvirongmentPreparedEvent事件
綁定環境
protected void bindToSpringApplication(ConfigurableEnvironment environment) {
        try {
            Binder.get(environment).bind("spring.main", Bindable.ofInstance(this));
        }
        catch (Exception ex) {
            throw new IllegalStateException("Cannot bind to SpringApplication", ex);
        }
    }
轉換環境

如果web環境變更為NONE則將StandardServletEnvironment轉換為StandardEnvironment

ConfigurationPropertySources.attach(environment)
public static void attach(Environment environment) {
        Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
        MutablePropertySources sources = ((ConfigurableEnvironment) environment)
                .getPropertySources();
        PropertySource<?> attached = sources.get("configurationProperties");
        if (attached != null && attached.getSource() != sources) {
            sources.remove("configurationProperties");
            attached = null;
        }
        if (attached == null) {
            sources.addFirst(new ConfigurationPropertySourcesPropertySource(
                    "configurationProperties",
                    new SpringConfigurationPropertySources(sources)));
        }
    }

最終這個sources對象的第一個位置放的是它自己,迴圈引用,這個具體的含義還有待挖掘

1


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 黃燜雞米飯最熱賣的外賣之一,國人都喜歡吃,吃過黃燜雞米飯的應該都知道,除了黃燜雞米飯主體外,還可以添加各種配菜,如土豆、香菇、鵪鶉蛋、青菜等。如果需要你來設計一套黃燜雞米飯結賬系統,你該如何設計呢? 前置條件:主體:黃燜雞米飯 價格:16,配菜:土豆 價格:2、香菇 價格:2、鵪鶉蛋 價格:2、青菜 ...
  • 橋接模式(Bridge): 橋接是用於把抽象化與實現化解耦,使得兩者可以獨立變化。 橋接模式的角色: 1)抽象化角色(Abstraction):它是用於定義抽象介面,通常是抽象類而不是介面,其中定義了一個Implementor(實現介面)類型的對象並可以維護該對象,它與Implementor之間具有 ...
  • 1. 下載安裝包 1 2 3 https://www.python.org/ftp/python/2.7.14/python-2.7.14.amd64.msi # 2.7安裝包 https://www.python.org/ftp/python/3.6.4/python-3.6.4-amd64.ex ...
  • ​一、生成器 1.定義(generator):一邊迴圈一邊計算下一個元素的機制/演算法 2.滿三個條件 (1)每次調用都能產生出for迴圈需要的下一個元素 (2)如果達到最後一個後,能夠爆出StopIteration異常 (3)可以被next函數調用 3.如何生成一個生成器 (1)直接使用 (2)如果 ...
  • # 1.在伺服器上 tomcat 的 bin目錄下找到並打開 catalina.sh 在文件中搜索: ``` JPDA_ADDRESS= ``` 找一個伺服器上沒有被使用的埠,填入,如50005,保存並退出。 > 如何知道某埠有沒有被占用? > 命令: > ``` > lsof -i:50005 ...
  • idea搭建spring源碼閱讀環境 安裝gradle Github下載Spring源碼 新建學習spring源碼的項目 idea搭建spring源碼閱讀環境 安裝gradle Github下載Spring源碼 新建學習spring源碼的項目 安裝gradle Github下載Spring源碼 新建 ...
  • 2019-09-23-23:48:00 今日所學的內容有: ...
  • 一、預設配置文件 二、指定配置文件 三、使用profile指定配置 ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...