SpringBoot-啟動過程
阿新 • • 發佈:2018-06-11
his class fin loader fig ron 工具類 sta PE
工作
Spring Boot的啟動,主要完成以下幾個工作:
- 收集創建ApplicationContext所需要的各種信息,創建並配置ApplicationContext。
- 啟動應用程序。
- 監聽應用啟動不同階段的事件。
組件
- SpringApplication:應用啟動的工具類,負責整個應用啟動工作。
- ApplicationContextInitalizer:自定義ApplicationContext的接口,用於在ApplicationContext調用refresh()之前對其進行配置。
- ApplicationListener:Spring應用的事件監聽器,監聽相關事件並做出響應。
- SpringApplicationRunListener:Spring Boot應用啟動的監聽器,用於在應用啟動的各個階段進行回調,方便用戶做出擴展。
啟動流程
源碼
1 public SpringApplication(Object... sources) { 2 initialize(sources); 3 } 4 public SpringApplication(ResourceLoader resourceLoader, Object... sources) { 5 this.resourceLoader = resourceLoader; 6 initialize(sources); 7 } 8 9 @SuppressWarnings({ "unchecked", "rawtypes" })10 private void initialize(Object[] sources) { 11 if (sources != null && sources.length > 0) { 12 this.sources.addAll(Arrays.asList(sources)); 13 } 14 //創建Environment 15 this.webEnvironment = deduceWebEnvironment(); 16 //獲取並保存ApplicationContextInitializer17 setInitializers((Collection) getSpringFactoriesInstances( 18 ApplicationContextInitializer.class)); 19 //獲取並保存ApplicationContextListener 20 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); 21 //保存程序入口,作為配置入口 22 this.mainApplicationClass = deduceMainApplicationClass(); 23 }
1 public ConfigurableApplicationContext run(String... args) { 2 StopWatch stopWatch = new StopWatch(); 3 stopWatch.start(); 4 ConfigurableApplicationContext context = null; 5 FailureAnalyzers analyzers = null; 6 configureHeadlessProperty(); 7 //獲取SpringApplicationRunListener 8 SpringApplicationRunListeners listeners = getRunListeners(args); 9 //調用監聽器,開始啟動 10 listeners.starting(); 11 try { 12 //生成ApplicationContext配置參數 13 ApplicationArguments applicationArguments = new DefaultApplicationArguments( 14 args); 15 //準備創建ApplicationContext的環境 16 ConfigurableEnvironment environment = prepareEnvironment(listeners, 17 applicationArguments); 18 Banner printedBanner = printBanner(environment); 19 //創建ApplicationContext 20 context = createApplicationContext(); 21 analyzers = new FailureAnalyzers(context); 22 //準備配置ApplicationContext的條件 23 prepareContext(context, environment, listeners, applicationArguments, 24 printedBanner); 25 //刷新ApplicationContext 26 refreshContext(context); 27 //執行刷新後的動作,包括執行ApplicationRunner和CommandRunner 28 afterRefresh(context, applicationArguments); 29 //啟動結束 30 listeners.finished(context, null); 31 stopWatch.stop(); 32 if (this.logStartupInfo) { 33 new StartupInfoLogger(this.mainApplicationClass) 34 .logStarted(getApplicationLog(), stopWatch); 35 } 36 return context; 37 } 38 catch (Throwable ex) { 39 handleRunFailure(context, listeners, analyzers, ex); 40 throw new IllegalStateException(ex); 41 } 42 }
SpringBoot-啟動過程