
在 Spring Boot 出現之前,我們要運行一個 Java Web 應用,首先需要有一個 Web 容器(例如 Tomcat 或 Jetty),然后將我們的 Web 應用打包后放到容器的相應目錄下,最后再啟動容器。
在 IDE 中也需要對 Web 容器進行一些配置,才能夠運行或者 Debug。而使用 Spring Boot 我們只需要像運行普通 JavaSE 程序一樣,run 一下 main() 方法就可以啟動一個 Web 應用了。這是怎么做到的呢?今天我們就一探究竟,分析一下 Spring Boot 的啟動流程。
概覽
回看我們寫的第一個 Spring Boot 示例,我們發現,只需要下面幾行代碼我們就可以跑起一個 Web 服務器:
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
去掉類的聲明和方法定義這些樣板代碼,核心代碼就只有一個 @SpringBootApplication 注解和 SpringApplication.run(HelloApplication.class, args) 了。而我們知道注解相當于是一種配置,那么這個 run() 方法必然就是 Spring Boot 的啟動入口了。
接下來,我們沿著 run() 方法來順藤摸瓜。進入 SpringApplication 類,來看看 run() 方法的具體實現:
public class SpringApplication {
......
public ConfigurableApplicationContext run(String... args) {
// 1 應用啟動計時開始
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 2 聲明上下文
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
// 3 設置 java.awt.headless 屬性
configureHeadlessProperty();
// 4 啟動監聽器
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
// 5 初始化默認應用參數
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 6 準備應用環境
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
// 7 打印 Banner(Spring Boot 的 LOGO)
Banner printedBanner = printBanner(environment);
// 8 創建上下文實例
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
// 9 構建上下文
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
// 10 刷新上下文
refreshContext(context);
// 11 刷新上下文后處理
afterRefresh(context, applicationArguments);
// 12 應用啟動計時結束
stopWatch.stop();
if (this.logStartupInfo) {
// 13 打印啟動時間日志
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 14 發布上下文啟動完成事件
listeners.started(context);
// 15 調用 runners
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
// 16 應用啟動發生異常后的處理
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
// 17 發布上下文就緒事件
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
......
}
Spring Boot 啟動時做的所有操作都這這個方法里面,當然在調用上面這個 run() 方法之前,還創建了一個 SpringApplication 的實例對象。因為上面這個 run() 方法并不是一個靜態方法,所以需要一個對象實例才能被調用。
可以看到,方法的返回值類型為
ConfigurableApplicationContext,這是一個接口,我們真正得到的是 AnnotationConfigServletWebServerApplicationContext 的實例。通過類名我們可以知道,這是一個基于注解的 Servlet Web 應用上下文(我們知道上下文(context)是 Spring 中的核心概念)。
上面對于 run() 方法中的每一個步驟都做了簡單的注釋,接下來我們選擇幾個比較有代表性的來詳細分析。
應用啟動計時
在 Spring Boot 應用啟動完成時,我們經常會看到類似下面內容的一條日志:
Started AopApplication in 2.732 seconds (JVM running for 3.734)
應用啟動后,會將本次啟動所花費的時間打印出來,讓我們對于啟動的速度有一個大致的了解,也方便我們對其進行優化。記錄啟動時間的工作是 run() 方法做的第一件事,在編號 1 的位置由 stopWatch.start() 開啟時間統計,具體代碼如下:
public void start(String taskName) throws IllegalStateException {
if (this.currentTaskName != null) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
}
// 記錄啟動時間
this.currentTaskName = taskName;
this.startTimeNanos = System.nanoTime();
}
然后到了 run() 方法的基本任務完成的時候,由 stopWatch.stop()(編號 12 的位置)對啟動時間做了一個計算,源碼也很簡單:
public void stop() throws IllegalStateException {
if (this.currentTaskName == null) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
// 計算啟動時間
long lastTime = System.nanoTime() - this.startTimeNanos;
this.totalTimeNanos += lastTime;
......
}
最后,在 run() 中的編號 13 的位置將啟動時間打印出來:
if (this.logStartupInfo) {
// 打印啟動時間
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
打印 Banner
Spring Boot 每次啟動是還會打印一個自己的 LOGO,如圖 8-6:

圖 8-6 Spring Boot Logo
這種做法很常見,像 Redis、Docker 等都會在啟動的時候將自己的 LOGO 打印出來。Spring Boot 默認情況下會打印那個標志性的“樹葉”和 “Spring” 的字樣,下面帶著當前的版本。
在 run() 中編號 7 的位置調用打印 Banner 的邏輯,最終由 SpringBootBanner 類的 printBanner() 完成。這個圖案定義在一個常量數組中,代碼如下:
class SpringBootBanner implements Banner {
private static final String[] BANNER = {
"",
" . ____ _ __ _ _",
" /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\",
"( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\",
" \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )",
" ' |____| .__|_| |_|_| |_\\__, | / / / /",
" =========|_|==============|___/=/_/_/_/"
};
......
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream printStream) {
for (String line : BANNER) {
printStream.println(line);
}
......
}
}
手工格式化了一下 BANNER 的字符串,輪廓已經清晰可見了。真正打印的邏輯就是 printBanner() 方法里面的那個 for 循環。
記錄啟動時間和打印 Banner 代碼都非常的簡單,而且都有很明顯的視覺反饋,可以清晰的看到結果。拿出來咱們做個熱身,配合斷點去 Debug 會有更加直觀的感受,尤其是打印 Banner 的時候,可以看到整個內容被一行一行打印出來,讓我想起了早些年用那些配置極低的電腦(還是 CRT 顯示器)運行著 Win98,經常會看到屏幕內容一行一行加載顯示。
創建上下文實例
下面我們來到 run() 方法中編號 8 的位置,這里調用了一個 createApplicationContext() 方法,該方法最終會調用 ApplicationContextFactory 接口的代碼:
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
try {
switch (webApplicationType) {
case SERVLET:
return new AnnotationConfigServletWebServerApplicationContext();
case REACTIVE:
return new AnnotationConfigReactiveWebServerApplicationContext();
default:
return new AnnotationConfigApplicationContext();
}
}
catch (Exception ex) {
throw new IllegalStateException("Unable create a default ApplicationContext instance, "
+ "you may need a custom ApplicationContextFactory", ex);
}
};
這個方法就是根據 SpringBootApplication 的 webApplicationType 屬性的值,利用反射來創建不同類型的應用上下文(context)。而屬性 webApplicationType 的值是在前面執行構造方法的時候由
WebApplicationType.deduceFromClasspath() 獲得的。通過方法名很容易看出來,就是根據 classpath 中的類來推斷當前的應用類型。
我們這里是一個普通的 Web 應用,所以最終返回的類型為 SERVLET。所以會返回一個
AnnotationConfigServletWebServerApplicationContext 實例。
構建容器上下文
接著我們來到 run() 方法編號 9 的 prepareContext() 方法。通過方法名,我們也能猜到它是為 context 做上臺前的準備工作的。
private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
......
// 加載資源
load(context, sources.toArray(new Object[0]));
listeners.contextLoaded(context);
}
在這個方法中,會做一些準備工作,包括初始化容器上下文、設置環境、加載資源等。
加載資源
上面的代碼中,又調用了一個很關鍵的方法——load()。這個 load() 方法真正的作用是去調用 BeanDefinitionLoader 類的 load() 方法。源碼如下:
class BeanDefinitionLoader {
......
void load() {
for (Object source : this.sources) {
load(source);
}
}
private void load(Object source) {
Assert.notNull(source, "Source must not be null");
if (source instanceof Class<?>) {
load((Class<?>) source);
return;
}
if (source instanceof Resource) {
load((Resource) source);
return;
}
if (source instanceof Package) {
load((Package) source);
return;
}
if (source instanceof CharSequence) {
load((CharSequence) source);
return;
}
throw new IllegalArgumentException("Invalid source type " + source.getClass());
}
......
}
可以看到,load() 方法在加載 Spring 中各種資源。其中我們最熟悉的就是 load((Class<?>) source) 和 load((Package) source) 了。一個用來加載類,一個用來加載掃描的包。
load((Class<?>) source) 中會通過調用 isComponent() 方法來判斷資源是否為 Spring 容器管理的組件。isComponent() 方法通過資源是否包含 @Component 注解(@Controller、@Service、@Repository 等都包含在內)來區分是否為 Spring 容器管理的組件。
而 load((Package) source) 方法則是用來加載 @ComponentScan 注解定義的包路徑。
刷新上下文
run() 方法編號10 的 refreshContext() 方法是整個啟動過程比較核心的地方。像我們熟悉的 BeanFactory 就是在這個階段構建的,所有非懶加載的 Spring Bean(@Controller、@Service 等)也是在這個階段被創建的,還有 Spring Boot 內嵌的 Web 容器要是在這個時候啟動的。
跟蹤源碼你會發現內部調用的是
ConfigurableApplicationContext.refresh(),ConfigurableApplicationContext 是一個接口,真正實現這個方法的有三個類:AbstractApplicationContext、ReactiveWebServerApplicationContext 和 ServletWebServerApplicationContext。
AbstractApplicationContext 為后面兩個的父類,兩個子類的實現比較簡單,主要是調用父類實現,比如 ServletWebServerApplicationContext 中的實現是這樣的:
public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
WebServer webServer = this.webServer;
if (webServer != null) {
webServer.stop();
}
throw ex;
}
}
主要的邏輯都在AbstractApplicationContext 中:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 1 準備將要刷新的上下文
prepareRefresh();
// 2 (告訴子類,如:ServletWebServerApplicationContext)刷新內部 bean 工廠
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3 為上下文準備 bean 工廠
prepareBeanFactory(beanFactory);
try {
// 4 允許在子類中對 bean 工廠進行后處理
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// 5 調用注冊為 bean 的工廠處理器
invokeBeanFactoryPostProcessors(beanFactory);
// 6 注冊攔截器創建的 bean 處理器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 7 初始化國際化相關資源
initMessageSource();
// 8 初始化事件廣播器
initApplicationEventMulticaster();
// 9 為具體的上下文子類初始化特定的 bean
onRefresh();
// 10 注冊監聽器
registerListeners();
// 11 實例化所有非懶加載的單例 bean
finishBeanFactoryInitialization(beanFactory);
// 12 完成刷新發布相應的事件(Tomcat 就是在這里啟動的)
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();
contextRefresh.end();
}
}
}
簡單說一下編號 9 處的 onRefresh() 方法,該方法父類未給出具體實現,需要子類自己實現,ServletWebServerApplicationContext 中的實現如下:
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
private void createWebServer() {
......
if (webServer == null && servletContext == null) {
......
// 根據配置獲取一個 web server(Tomcat、Jetty 或 Undertow)
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
......
}
......
}
factory.getWebServer(getSelfInitializer()) 會根據項目配置得到一個 Web Server 實例,這里跟下一篇將要談到的自動配置有點關系。