此篇文章開始解析SpringApplication的run
方法具體代碼如下:
public ConfigurableApplicationContext run(String... args) {
1.StopWatch stopWatch = new StopWatch();
2.stopWatch.start();
3.ConfigurableApplicationContext context = null;
4.Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
5.configureHeadlessProperty();
6.SpringApplicationRunListeners listeners = getRunListeners(args);
7.listeners.starting();
try {
8. ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
9. ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
10. configureIgnoreBeanInfo(environment);
11. Banner printedBanner = printBanner(environment);
12. context = createApplicationContext();
13. exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
14. prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
15. refreshContext(context);
16. afterRefresh(context, applicationArguments);
17. stopWatch.stop();
18. if (this.logStartupInfo) {
19. new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
20. listeners.started(context);
21. callRunners(context, applicationArguments);
}
catch (Throwable ex) {
22. handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
23. listeners.running(context);
}
catch (Throwable ex) {
24. handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
本章主要解析1-7小節。
首先返回的對象
ConfigurableApplicationContext
就是applicationContext
子類,前者相比后者提供了更多的功能,比如實現Lifecycle, Closeable
接口 更好的管理bean的聲明周期,還有其他的 諸如:addBeanFactoryPostProcessor,setParent,setId,addApplicationListener,addProtocolResolver
等額外的功能。
StopWatch 主要是spring為了計算加載耗時產生的。
其內部包含一個list(代表任務的個數),當開始調用start方法后,然后調用stop,都會記錄當前時間和start時間的耗時,然后封裝成一個任務對象加入到StopWatch內部的list中,其中start和stop方法必須成對出現。
SpringBootExceptionReporter---用來支持報告關于啟動的錯
首先其會在第13行代碼從配置文件中獲取具體的實現類,當springboot啟動工程出現異常,比如22,24行時候,就會調用handleRunFailure
方法,具體如下:
private void handleRunFailure(ConfigurableApplicationContext context,
Throwable exception,
Collection<SpringBootExceptionReporter> exceptionReporters,
SpringApplicationRunListeners listeners) {
try {
try {
handleExitCode(context, exception);
if (listeners != null) {
listeners.failed(context, exception);
}
}
finally {
reportFailure(exceptionReporters, exception);
if (context != null) {
context.close();
}
}
}
catch (Exception ex) {
logger.warn("Unable to close ApplicationContext", ex);
}
ReflectionUtils.rethrowRuntimeException(exception);
}
首先看handleExitCode(context, exception)
private void handleExitCode(ConfigurableApplicationContext context,
Throwable exception) {
int exitCode = getExitCodeFromException(context, exception);
if (exitCode != 0) {
if (context != null) {
context.publishEvent(new ExitCodeEvent(context, exitCode));
}
SpringBootExceptionHandler handler = getSpringBootExceptionHandler();
if (handler != null) {
handler.registerExitCode(exitCode);
}
}
}
上述代碼的意思就是從異常中獲取退出狀態碼,如果退出狀態碼不等于0,就通過ConfigurableApplicationContext 發布退出事件,SpringBootExceptionHandler 注冊下該狀態碼。
下面主要看reportFailure(exceptionReporters, exception);
private void reportFailure(Collection<SpringBootExceptionReporter> exceptionReporters,
Throwable failure) {
try {
for (SpringBootExceptionReporter reporter : exceptionReporters) {
if (reporter.reportException(failure)) {
registerLoggedException(failure);
return;
}
}
}
catch (Throwable ex) {
// Continue with normal handling of the original failure
}
if (logger.isErrorEnabled()) {
logger.error("Application run failed", failure);
registerLoggedException(failure);
}
}
上述代碼就是依次調用SpringBootExceptionReporter的reportException方法(該方法主要是調用analyzer的集合去分析異常,如果有analyzer能分析成功,就把異常打印出來) 如果成功了在把改異常注冊到SpringBootExceptionHandler中。
configureHeadlessProperty();
主要是用來設置headless模式,具體的好處如下
Headless模式是在缺少顯示屏、鍵盤或者鼠標是的系統配置。在java.awt.toolkit和java.awt.graphicsenvironment類中有許多方法,除了對字體、圖形和打印的操作外還可以調用顯示器、鍵盤和鼠標的方法。但是有一些類中,比如Canvas和Panel,可以在headless模式下執行
如果名字為java.awt.headless的系統屬性被設置true,那么headless工具包就會被使用。應用程序可以執行如下操作:
(1)創建輕量級組件。
(2)收集關于可用的字體、字體指標和字體設置的信息。
(3)設置顏色來渲染準備圖片。
(4)創造和獲取圖像,為渲染準備圖片。
(5)使用java.awt.PrintJob,java.awt.print.,和javax.print.類里德打印
SpringApplicationRunListeners
首先SpringApplicationRunListeners
是一個集合類,內部包含一個log和包含SpringApplicationRunListener的List。
而SpringApplicationRunListener
主要是監聽SpringApplication對象的,里面的方法都定義了在何時調用SpringApplicationRunListener
的各種方法。
下面的每一個方法SpringApplicationRunListener 都把其包裝成一個事件,在spring容器還未成功refreshed之前都是使用SimpleApplicationEventMulticaster 去尋找對該事件感興趣的ApplicationListener,然后調用其onApplicationEvent方法
1.starting:當SpringApplication對象的run方法剛啟動的時候(依靠SimpleApplicationEventMulticaster)
2.environmentPrepared:在environment Prepared 但是spring容器還未創建的時候(依靠SimpleApplicationEventMulticaster)
3.contextPrepared:當spring容器已經創建且準備好了,(目前是空的實現)
4.contextLoaded:當spring容器已經loaded 且未refresh 。load就是將我們的primaryClass注冊到spring容器中,(依靠SimpleApplicationEventMulticaster) 同時將之前獲取到的ApplicationListener都加入到spring容器中,此時如果ApplicationListener還是ApplicationContextAware的也要調用其setApplicationContext方法。
5.started:spring容器已經刷新過且應用已經啟動,但是CommandLineRunners和ApplicationRunners還為調用,直接通過spring容器自己發送(因為ApplicationListener已經加入spring容器)
6.running:我們已經調用了CommandLineRunners,直接通過spring容器自己發送(因為ApplicationListener已經加入spring容器)
7.failed:當異常發生的時候就調用這個,如果spring容器沒有loaded 或者沒有激活就使用SimpleApplicationEventMulticaster,否則還是依靠spring容器自己
SpringApplicationRunListener,ApplicationListener和SimpleApplicationEventMulticaster的區別
- 1.SpringApplicationRunListener的那些方法底層還是依靠spring容器去發布事件
- 2.底層還是會被ApplicationListener給監聽到
- 3.在spring容器prepareContext調用之后會將ApplicationListener都加入到SimpleApplicationEventMulticaster,在這之后所有的事件都會lazy發送,即先存在earlyApplicationEvents。等到spring容器refresh之后注冊所有ApplicationListener,然后在統一發送之前存儲的事件。