SpringApplication到底run了什麼(下)

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

在上篇文章中 "SpringApplication到底run了什麼(上)" 中,我們分析了下麵這個run方法的前半部分,本篇文章繼續開工 6. 獲取系統屬性 但是這個屬性的作用還真不知道。。 7. 列印banner 8. 根據當前環境創建ApplicationContext 基於咱們的Servlet ...


在上篇文章中SpringApplication到底run了什麼(上)中,我們分析了下麵這個run方法的前半部分,本篇文章繼續開工

    public ConfigurableApplicationContext run(String... args) {
            //。。。
            //接上文繼續
            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, listeners, exceptionReporters, ex);
            throw new IllegalStateException(ex);
        }
        listeners.running(context);
        return context;
    }
  1. 獲取系統屬性spring.beaninfo.ignore
private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
        if (System.getProperty(
                CachedIntrospectionResults."spring.beaninfo.ignore") == null) {
            Boolean ignore = environment.getProperty("spring.beaninfo.ignore",
                    Boolean.class, Boolean.TRUE);
            System.setProperty(CachedIntrospectionResults."spring.beaninfo.ignore",
                    ignore.toString());
        }
    }

但是這個屬性的作用還真不知道。。

  1. 列印banner
  2. 根據當前環境創建ApplicationContext
protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
                    break;
                case REACTIVE:
                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                    break;
                default:
                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
                }
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                        "Unable create a default ApplicationContext, "
                                + "please specify an ApplicationContextClass",
                        ex);
            }
        }
        return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

基於咱們的Servlet環境,所以創建的ApplicationContext為AnnotationConfigServletWebServerApplicationContext

  1. 載入SpringBootExceptionReporter,這個類里包含了SpringBoot啟動失敗後異常處理相關的組件
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
            Class<?>[] parameterTypes, Object... args) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Set<String> names = new LinkedHashSet<>(
                SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
                classLoader, args, names);
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }

10 prepareContext 這一塊還是比較長的

private void prepareContext(ConfigurableApplicationContext context,
        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);
    postProcessApplicationContext(context);
    applyInitializers(context);
    listeners.contextPrepared(context);
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }

    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);                               
    if (printedBanner != null) {
        context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }

    // Load the sources
    Set<Object> sources = getAllSources();                     
    Assert.notEmpty(sources, "Sources must not be empty");       
    load(context, sources.toArray(new Object[0]));
    listeners.contextLoaded(context);
}
1. 第一行,將context中相關的environment全部替換

public void setEnvironment(ConfigurableEnvironment environment) {
    super.setEnvironment(environment);            // 設置context的environment
    this.reader.setEnvironment(environment);    // 實例化context的reader屬性的conditionEvaluator屬性
    this.scanner.setEnvironment(environment);    // 設置context的scanner屬性的environment屬性
}
2. 上下文後處理

protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
    if (this.beanNameGenerator != null) {
        context.getBeanFactory().registerSingleton(
                AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
                this.beanNameGenerator);
    }
    if (this.resourceLoader != null) {
        if (context instanceof GenericApplicationContext) {
            ((GenericApplicationContext) context)
                    .setResourceLoader(this.resourceLoader);
        }
        if (context instanceof DefaultResourceLoader) {
            ((DefaultResourceLoader) context)
                    .setClassLoader(this.resourceLoader.getClassLoader());
        }
    }
}

這一塊預設beanNameGeneratorresourceLoader都是空的,只有當我們自定義這兩個對象時才會把容器內的bean替換
3. 執行所有的ApplicationContextInitializerinitialize方法


protected void applyInitializers(ConfigurableApplicationContext context) {
    for (ApplicationContextInitializer initializer : getInitializers()) {
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
                initializer.getClass(), ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        initializer.initialize(context);
    }
}
4. `listeners.contextPrepared(context)`這是個空方法,沒有實現,一個Spring的擴展點
5. 列印profile
6. 註冊bean:`springApplicationArguments`
7. 發佈事件
public void contextLoaded(ConfigurableApplicationContext context) {
        for (ApplicationListener<?> listener : this.application.getListeners()) {
            if (listener instanceof ApplicationContextAware) {
                ((ApplicationContextAware) listener).setApplicationContext(context);
            }
            context.addApplicationListener(listener);
        }
        this.initialMulticaster.multicastEvent(
                new ApplicationPreparedEvent(this.application, this.args, context));
    }

這裡不僅發佈了ApplicationPreparedEvent事件,還往實現了ApplicationContextAware介面的監聽器中註入了context容器
8. load,其實就是創建了一個BeanDefinitionLoader對象

protected void load(ApplicationContext context, Object[] sources) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
        }
        BeanDefinitionLoader loader = createBeanDefinitionLoader(
                getBeanDefinitionRegistry(context), sources);
        if (this.beanNameGenerator != null) {
            loader.setBeanNameGenerator(this.beanNameGenerator);
        }
        if (this.resourceLoader != null) {
            loader.setResourceLoader(this.resourceLoader);
        }
        if (this.environment != null) {
            loader.setEnvironment(this.environment);
        }
        loader.load();
    }
  1. 容器的初始化refreshContext
    這個方法最後還是調用的AbstractApplicationContext類的refresh方法,由於篇幅過長這裡就不展開了,感興趣的同學可以參考這篇文章:基於註解的SpringIOC源碼解析
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // 記錄容器的啟動時間、標記“已啟動”狀態、檢查環境變數
      prepareRefresh();
      // 初始化BeanFactory容器、註冊BeanDefinition
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      // 設置 BeanFactory 的類載入器,添加幾個 BeanPostProcessor,手動註冊幾個特殊的 bean
      prepareBeanFactory(beanFactory);
      try {
         // 擴展點
         postProcessBeanFactory(beanFactory);
         // 調用 BeanFactoryPostProcessor 各個實現類的 postProcessBeanFactory(factory) 方法
         invokeBeanFactoryPostProcessors(beanFactory);
         // 註冊 BeanPostProcessor 的實現類
         registerBeanPostProcessors(beanFactory);
         // 初始化MessageSource
         initMessageSource();
         // 初始化事件廣播器
         initApplicationEventMulticaster();
         // 擴展點
         onRefresh();
         // 註冊事件監聽器
         registerListeners();
         // 初始化所有的 singleton beans
         finishBeanFactoryInitialization(beanFactory);
         // 廣播事件
         finishRefresh();
      }
      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }
         // 銷毀已經初始化的的Bean
         destroyBeans();
         // 設置 'active' 狀態
         cancelRefresh(ex);
         throw ex;
      }
      finally {
         // 清除緩存
         resetCommonCaches();
      }
   }
}
  1. afterRefresh
    這裡沒有任何實現,Spring留給我們的擴展點
  2. 停止之前啟動的計時裝置,然後發送ApplicationStartedEvent事件
  3. 調用系統中ApplicationRunner以及CommandLineRunner介面的實現類,關於這兩個介面的使用可以參考我的這篇文章:Java項目啟動時執行指定方法的幾種方式
private void callRunners(ApplicationContext context, ApplicationArguments args) {
        List<Object> runners = new ArrayList<>();
        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        AnnotationAwareOrderComparator.sort(runners);
        for (Object runner : new LinkedHashSet<>(runners)) {
            if (runner instanceof ApplicationRunner) {
                callRunner((ApplicationRunner) runner, args);
            }
            if (runner instanceof CommandLineRunner) {
                callRunner((CommandLineRunner) runner, args);
            }
        }
    }
  1. 異常處理
  2. 發送ApplicationReadyEvent事件

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

-Advertisement-
Play Games
更多相關文章
  • 靜態代理類: 由程式員創建或由特定工具自動生成源代碼,再對其編譯。在程式運行前,代理類的.class文件就已經存在了 動態代理類: 與靜態代理類對照的是動態代理類,動態代理類的位元組碼在程式運行時由Java反射機制動態生成,無需程式員手工編寫它的源代碼。動態代理類不僅簡化了編程工作,而且提高了軟體系統 ...
  • 場景 系統架構設計師考試,屬於全國電腦技術與軟體專業技術資格考試(簡稱電腦軟體資格考試)中的一個高級考試。 系統架構設計師考試,考試不設學歷與資歷條件,不論年齡和專業,考生可根據自己的技術水平,選擇合適的級別合適的資格,但一次考試只能報考一種資格。 之前分享過一次mp3教程資源。 https:/ ...
  • 裝飾者模式(wrapper): 允許向一個現有的對象添加新的功能,同時又不改變其結構。裝飾器模式是一種用於代替繼承的技術,無需通過繼承增加子類就能擴展對象的新功能。使用對象的關聯關係代替繼承關係,更加靈活,同時避免類型體系的快速膨脹。 示例:英雄學習技能 裝飾者模式有四個角色: 1)抽象構建(Com ...
  • PHP字元串函數是核心的一部分。無需安裝即可使用這些函數 ...
  • 一 ORM簡介 MVC或者MVC框架中包括一個重要的部分,就是ORM,它實現了數據模型與資料庫的解耦,即數據模型的設計不需要依賴於特定的資料庫,通過簡單的配置就可以輕鬆更換資料庫,這極大的減輕了開發人員的工作量,不需要面對因資料庫變更而導致的無效勞動 ORM是“對象 關係 映射”的簡稱。(Objec ...
  • 預設方法 步驟 1 : 什麼是預設方法 預設方法是JDK8新特性,指的是介面也可以提供具體方法了,而不像以前,只能提供抽象方法 Mortal 這個介面,增加了一個 預設方法 revive,這個方法有實現體,並且被聲明為了 default package charactor; public inter ...
  • 一、記憶體分析 代碼:引用可以是局部變數也可以是成員變數 二、對象之間建立關係 二、源碼: D34_husband_and_wife.java 地址: https://github.com/ruigege66/Java/blob/master/D34_husband_and_wife.java​ 2. ...
  • 夢中驚醒 在Tomcat的線程池裡,有這樣一個線程,自打出生後,從來不去幹活兒,有好多次走出線程池“這座大山”去看世界的機會,都被他拱手讓給了弟兄們。弟兄們給他取了個名字叫二師兄。沒錯,好吃懶做,飽了睡,醒了吃。這不,又迷迷糊糊睡著了,還打呼嚕呢。“快起來,起來,幹活去了”,有人在喊他。只見二師兄轉 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...