工作
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 //获取并保存ApplicationContextInitializer 17 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 }