Skip to content

Instantly share code, notes, and snippets.

@albert-hg
Last active August 11, 2020 06:16
Show Gist options
  • Save albert-hg/ce9c3c5da4884670dc204c18f2969ab5 to your computer and use it in GitHub Desktop.
Save albert-hg/ce9c3c5da4884670dc204c18f2969ab5 to your computer and use it in GitHub Desktop.
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
// 1. 設定系統的 Property
configureHeadlessProperty();
// 2. 初始化 Listener
SpringApplicationRunListeners listeners = getRunListeners(args);
// 3. 通知 Listener "Spring Boot 開始執行"
listeners.starting();
try {
// 4. 將傳入 run() 的參數轉換為 ApplicationArguments 的配置物件
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 5. 透過 配置 與 Listener 建立 配置環境
ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);
// 6. 檢查是否有被忽略的配置,並將忽略的配置設定置系統的 Property
configureIgnoreBeanInfo(environment);
// 7. 印出 Banner
Banner printedBanner = printBanner(environment);
// 8. 建立 ApplicationContext 容器
context = createApplicationContext();
// 9. 設定容器的啟動類型
context.setApplicationStartup(this.applicationStartup);
// 10. 取得 Bean Factory Class 的 Instance
exceptionReporters =getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class<?>[] { ConfigurableApplicationContext.class },
context
);
// 11. 載入容器
prepareContext(context,environment,listeners,applicationArguments,printedBanner);
// 12. 刷新容器
refreshContext(context);
// afterRefresh 目前沒有作用
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
// 13. 建立 Logger 並印出相關建構容器的資訊
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 14. Listener 開始監聽容器
listeners.started(context);
// 15. 執行 @Bean 底下的 static methiods
callRunners(context, applicationArguments);
} catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
// 16. 執行容器
listeners.running(context);
} catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment