SpringBoot執行過程實例分析
每個Spring Boot專案都有一個主程式啟動類,在主程式啟動類別中有一個啟動專案的main()方法,在該方法中透過執行SpringApplication.run()即可啟動整個Spring Boot程式。
問題:那麼SpringApplication.run()方法到底是如何做到啟動Spring Boot專案的呢?
下面我們查看run()方法內部的原始碼,核心程式碼具體如下:
@SpringBootApplication public class SpringbootDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootDemoApplication.class, args); } }
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class[]{primarySource}, args); } public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return (new SpringApplication(primarySources)).run(args); }
從上述原始碼可以看出,SpringApplication.run()方法內部執行了兩個操作,分別是SpringApplication實例的初始化建立和呼叫run()啟動項目,這兩個階段的實作具體說明如下
#1. SpringApplication實例的初始化創建
查看SpringApplication實例物件初始化創建的源碼訊息,核心代碼具體如下
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) { this.sources = new LinkedHashSet(); this.bannerMode = Mode.CONSOLE; this.logStartupInfo = true; this.addCommandLineProperties = true; this.addConversionService = true; this.headless = true; this.registerShutdownHook = true; this.additionalProfiles = new HashSet(); this.isCustomEnvironment = false; this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); // 把项目启动类.class设置为属性存储起来 this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); // 判断当前webApplicationType应用的类型 this.webApplicationType = WebApplicationType.deduceFromClasspath(); // 设置初始化器(Initializer),最后会调用这些初始化器 this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); // 设置监听器(Listener) this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); // 用于推断并设置项目main()方法启动的主程序启动类 this.mainApplicationClass = this.deduceMainApplicationClass();
從上述原始碼可以看出,SpringApplication的初始化過程主要包括4部分,具體說明如下。
(1)this.webApplicationType = WebApplicationType.deduceFromClasspath()
用來判斷目前webApplicationType應用的型別。 deduceFromClasspath()方法用於查看Classpath類路徑下是否存在某個特徵類,從而判斷當前webApplicationType類型是SERVLET應用(Spring 5之前的傳統MVC應用)還是REACTIVE應用(Spring 5開始出現的WebFlux交互式應用)
(2)this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class))
用於SpringApplication應用的初始化器設定。在初始化器設定過程中,會使用Spring類別載入器SpringFactoriesLoader從META-INF/spring.factories類別路徑下的META-INF下的spring.factores檔案中取得所有可用的應用初始化器類別ApplicationContextInitializer。
(3)this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class))
#用於SpringApplication應用的監聽器設定。監聽器設定的過程與上一步初始化器設定的過程基本上一樣,也是使用SpringFactoriesLoader從META-INF/spring.factories類別路徑下的META-INF下的spring.factores檔案中取得所有可用的監聽器類別ApplicationListener。
(4)this.mainApplicationClass = this.deduceMainApplicationClass()
用於推斷並設定專案main()方法啟動的主程式啟動類別
#2.專案的初始化啟動
分析完(new SpringApplication(primarySources)).run(args)原始碼前一部分SpringApplication實例物件的初始化建立後,查看run(args)方法執行的專案初始化啟動過程,核心程式碼具體如下:
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList(); this.configureHeadlessProperty(); // 第一步:获取并启动监听器 SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(); Collection exceptionReporters; try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); // 第二步:根据SpringApplicationRunListeners以及参数来准备环境 ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); this.configureIgnoreBeanInfo(environment); // 准备Banner打印器 - 就是启动Spring Boot的时候打印在console上的ASCII艺术字体 Banner printedBanner = this.printBanner(environment); // 第三步:创建Spring容器 context = this.createApplicationContext(); exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, new Object[]{context}); // 第四步:Spring容器前置处理 this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); // 第五步:刷新容器 this.refreshContext(context); // 第六步:Spring容器后置处理 this.afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); } // 第七步:发出结束执行的事件 listeners.started(context); // 返回容器 this.callRunners(context, applicationArguments); } catch (Throwable var10) { this.handleRunFailure(context, var10, exceptionReporters, listeners); throw new IllegalStateException(var10); } try { listeners.running(context); return context; } catch (Throwable var9) { this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners) null); throw new IllegalStateException(var9); } }
從上述原始碼可以看出,專案初始化啟動過程大致包含以下部分:
第一步:取得並啟動監聽器
this.getRunListeners (args)和listeners.starting()方法主要用於取得SpringApplication實例初始化過程中初始化的SpringApplicationRunListener監聽器並執行。
第二步:根據SpringApplicationRunListeners以及參數來準備環境
this.prepareEnvironment(listeners, applicationArguments)方法主要用於對專案運行環境進行預設置,同時透過this.configureIgnoreBeanInfo(environment )方法排除一些不需要的運行環境
第三步:建立Spring容器
根據webApplicationType進行判斷, 決定容器類型,如果該類型為SERVLET類型,會透過反射來裝載對應的字節碼,也就是AnnotationConfigServletWebServerApplicationContext,接著使用先前初始化設定的context(應用上下文環境)、environment(專案運行環境)、listeners(運行監聽器)、applicationArguments(專案參數)和printedBanner(專案圖示資訊)進行應用上下文的組裝配置,並刷新配置
第四步:Spring容器前置處理
這一步主要是在容器刷新之前的準備動作。設定容器環境,包括各種變數等等,其中包含一個非常關鍵的操作:將啟動類別注入容器,為後續開啟自動化配置奠定基礎
第五步:刷新容器
開啟刷新spring容器,透過refresh方法對整個IOC容器的初始化(包括bean資源的定位,解析,註冊等等),同時向JVM運行時註冊一個關機鉤子,在JVM關機時會關閉這個上下文,除非當時它已經關閉
第六步:Spring容器後置處理
擴展接口,設計模式中的模板方法,預設為空實現。如果有自訂需求,可以重寫該方法。例如列印一些啟動結束log,或一些其它後置處理。
第七步驟:發出結束執行的事件
取得EventPublishingRunListener監聽器,並執行其started方法,並且將建立的Spring容器傳進去了,建立一個ApplicationStartedEvent事件,並執行ConfigurableApplicationContext的
publishEvent方法,也就是說這裡是在Spring容器中發布事件,並不是在SpringApplication中發布事件,和前面的starting是不同的,前面的starting是直接向SpringApplication中的監聽器發布啟動事件。
第八步驟:執行Runners
##用於呼叫專案中自訂的執行器XxxRunner類,使得在專案啟動完成後立即執行一些特定程式。其中,Spring Boot提供的執行器介面有ApplicationRunner 和CommandLineRunner兩種,在使用時只需要自訂一個執行器類別實作其中一個介面並重寫對應的run()方法接口,然後Spring Boot專案啟動後會立即執行這些特定程式
下面,透過一個Spring Boot執行流程圖,讓大家更清楚的知道Spring Boot的整體執行流程和主要啟動階段:
以上是SpringBoot執行過程實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Jasypt介紹Jasypt是一個java庫,它允許開發員以最少的努力為他/她的專案添加基本的加密功能,並且不需要對加密工作原理有深入的了解用於單向和雙向加密的高安全性、基於標準的加密技術。加密密碼,文本,數字,二進位檔案...適合整合到基於Spring的應用程式中,開放API,用於任何JCE提供者...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt好處保護我們的系統安全,即使程式碼洩露,也可以保證資料來源的

一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

使用場景1、下單成功,30分鐘未支付。支付超時,自動取消訂單2、訂單簽收,簽收後7天未進行評估。訂單超時未評價,系統預設好評3、下單成功,商家5分鐘未接單,訂單取消4、配送超時,推播簡訊提醒…對於延時比較長的場景、即時性不高的場景,我們可以採用任務調度的方式定時輪詢處理。如:xxl-job今天我們採

springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

在Springboot+Mybatis-plus不使用SQL語句進行多表添加操作我所遇到的問題準備工作在測試環境下模擬思維分解一下:創建出一個帶有參數的BrandDTO對像模擬對後台傳遞參數我所遇到的問題我們都知道,在我們使用Mybatis-plus中進行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類的工具,你只能去配置對應的Mapper.xml文件,配置又臭又長的ResultMap,然後再寫對應的sql語句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

在專案中,很多時候需要用到一些配置信息,這些信息在測試環境和生產環境下可能會有不同的配置,後面根據實際業務情況有可能還需要再做修改。我們不能將這些設定在程式碼中寫死,最好是寫到設定檔中,例如可以把這些資訊寫到application.yml檔案中。那麼,怎麼在程式碼裡取得或使用這個位址呢?有2個方法。方法一:我們可以透過@Value註解的${key}即可取得設定檔(application.yml)中和key對應的value值,這個方法適用於微服務比較少的情形方法二:在實際專案中,遇到業務繁瑣,邏
