1. 程式人生 > 程式設計 >Spring Boot啟動流程斷點過程解析

Spring Boot啟動流程斷點過程解析

這篇文章主要介紹了Spring Boot啟動流程斷點過程解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

啟動入口

跟進run方法 : 一個用來使用預設的配置從特定的源執行SpringApplication的靜態幫助類。

這個類有兩個過載方法,另一個用來傳入多個源。通常,單個引數方法是陣列方法的一個特例

建立一個新的SpringApplication例項。這個應用程式上下文會從特定的源載入Beans,這個例項會在呼叫run方法之前被定製化。

Web應用程式型別的列舉:WebApplicationType,包含NONE(不是web應用),SERVLET(基於Servlet的web應用),REACTIVE(基於Reactive的web應用)

  • 直接jar包執行不使用web容器
  • 使用嵌入式的Servlet web容器
  • 使用反應式的web容器

setInitializers((Collection) getSpringFactoriesInstances(
  ApplicationContextInitializer.class));

用於建立和載入Spring工廠方法例項

4.執行SpringApplication的run方法

Java SPI在 Spring Boot中的應用

SpringBoot底層的自動化都是由這些SPI實現類來實現的:初始化,監聽器,自動配置匯入監聽器,自動配置匯入過濾器,自動配置,失敗分析器,可用模板提供者

Spring Boot找到main方式的方式

通過拋異常的形式來獲取堆疊資訊,再獲取啟動類的資訊。

以上都是new SpringBootApplication的過程,下面分析run方法

/**
* Run the Spring application,creating and refreshing a new
* {@link ApplicationContext}.
* 執行一個Spring應用,建立和重新整理一個新的ApplicationContext
* @param args the application arguments (usually passed from a Java main method)
* 應用引數通過java main方法傳遞過來
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
// 任務計時器工具,可同時計數多個任務
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//ApplicationContext是Spring的中心介面,為應用提供配置:1bean工廠2載入資源3註冊的監聽器釋出事件4解析訊息
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//headless 模式:伺服器端模式,表示系統沒有鍵盤滑鼠等前端應用
configureHeadlessProperty();
//監聽器容器,對run方法各個階段事件進行監聽,觀察者模式
SpringApplicationRunListeners listeners = getRunListeners(args);
//監聽相應的事件,SpringApplicationEvent下的一個實現
listeners.starting();
try {
//提供了對於執行SpringApplication引數的訪問
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//環境配置:是servlet,reactive或者java應用環境,觸發evn準備好的事件
ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);
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,ex,exceptionReporters,listeners);
throw new IllegalStateException(ex);
}

try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context,null);
throw new IllegalStateException(ex);
}
return context;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。