SpringBoot2原理—SpringApplication的执行流程
由于在Spring Boot的入口类中,我们通常是通过调用SpringApplication的run方法来启动Spring Boot项目。这节我们来深入学习下SpringApplication的一些细节。
1.自定义SpringApplication
默认的我们都是直接通过SpringApplication的run方法来直接启动Spring Boot,其实我们可以通过一些API来调整某些行为。
1.1 通过SpringApplication API调整
我们新建一个SpringBoot项目,Spring Boot版本为2.1.8.RELEASE,artifactId为SpringApplication,并引入spring-boot-starter-web依赖。项目结构如下所示:
我们将入口类的代码改为:
SpringApplication application = new SpringApplication(DemoApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.setWebApplicationType(WebApplicationType.NONE);
application.setAdditionalProfiles("dev");
application.run(args);
通过调用SpringApplication的方法,我们关闭了Banner的打印,设置应用环境为非WEB应用,profiles指定为dev。除此之外,SpringApplication还包含了许多别的方法,具体可以查看源码或者官方文档:
1.2 通过SpringApplicationBuilder API调整
SpringApplicationBuilder提供了Fluent API,可以实现链式调用,下面的代码和上面的效果一致,但在编写上较为方便:
new SpringApplicationBuilder(DemoApplication.class)
.bannerMode(Banner.Mode.OFF)
.web(WebApplicationType.NONE)
.profiles("dev")
.run(args);
2.SpringApplication准备阶段
SpringApplication的生命周期阶段大致可以分为准备阶段和运行阶段。
通过源码来查看SpringApplication的有参构造器:
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//第一步:加载我们配置的Spring Boot Bean源
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//第二步:推断当前Spring Boot应用类型
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//第三步:加载应用上下文初始器ApplicationContextInitializer
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//第四步:加载应用事件监听器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//第五步:推断运行Spring Boot应用的入口类
this.mainApplicationClass = deduceMainApplicationClass();
}
通过有参构造器里的代码我们可以将SpringApplication的准备阶段分为以下几个步骤:
2.1 配置源
构造器中this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));这行代码用于加载我们配置的Spring Boot Bean源。通常我们使用SpringApplication或者SpringApplicationBuilder的构造器来直接指定源。
所谓的Spring Boot Bean源指的是某个被@SpringBootApplication注解标注的类,比如入口类:
我们也可以将上面的代码改为下面这种方式:
public class DemoApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(ApplicationResource.class);
application.run(args);
}
@SpringBootApplication
public static class ApplicationResource {
}
}
这样也是可行的。
接下来查看SpringApplication的单个参数构造器:
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
从这里我们可以看出除了配置单个源外,还可以配置多个源。
2.2 推断应用类型
构造器中这行this.webApplicationType = WebApplicationType.deduceFromClasspath();代码用于推断当前Spring Boot应用类型。
Spring Boot 2.0后,应用可以分为下面三种类型:
-
WebApplicationType.NONE:非WEB类型;
-
WebApplicationType.REACTIVE:Web Reactive类型;
-
WebApplicationType.SERVLET:Web Servlet类型。
WebApplicationType.deduceFromClasspath()方法根据当前应用ClassPath中是否存在相关的实现类来判断应用类型到底是哪个,deduceFromClasspath方法的源码如下所示:
private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
"org.springframework.web.context.ConfigurableWebApplicationContext" };
private static final String WEBMVC_INDICATOR_CLASS = "org.springframework." + "web.servlet.DispatcherServlet";
private static final String WEBFLUX_INDICATOR_CLASS = "org." + "springframework.web.reactive.DispatcherHandler";
private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";
private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";
private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}
我们也可以直接通过SpringApplication的setWebApplicationType方法或者SpringApplicationBuilder的web方法来指定当前应用的类型。
2.3 加载应用上下文初始器
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));用于加载应用上下文初始器ApplicationContextInitializer。
getSpringFactoriesInstances方法的源码如下所示:
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
上面代码利用Spring工厂加载机制,实例化ApplicationContextInitializer实现类,并进行排序。
所以我们可以通过实现ApplicationContextInitializer接口用于在Spring Boot应用初始化之前执行一些自定义操作。
举个例子,在com.example.demo下新建initializer包,然后创建一个HelloApplicationContextInitializer类,实现ApplicationContextInitializer接口:
@Order(Ordered.HIGHEST_PRECEDENCE)
public class HelloApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("ConfigurableApplicationContext.id - " + applicationContext.getId());
}
}
上面代码中实现了initialize方法,并且使用@Order注解指定优先级。其中Ordered.HIGHEST_PRECEDENCE等于Integer.MIN_VALUE,Ordered.LOWEST_PRECEDENCE等于Integer.MAX_VALUE。所以数值越小,优先级越高。
除了使用@Order注解来指定优先级外,我们也可以通过实现org.springframework.core.Ordered接口的getOrder方法来指定优先级。
接着我们来创建一个优先级比HelloApplicationContextInitializer低的Initializer —— AfterHelloApplicationContextInitializer:
public class AfterHelloApplicationContextInitializer implements ApplicationContextInitializer, Ordered {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("AfterHelloApplicationContextInitializer: " + applicationContext.getId());
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
上面通过getOrder方法来指定了优先级为最低优先级。
创建好后,我们还需在工厂配置文件里配置这两个实现类。在resources目录下新建META-INF目录,并创建spring.factories文件:
# Initializers
org.springframework.context.ApplicationContextInitializer=\
com.allan.demo.initializer.HelloApplicationContextInitializer,\
com.allan.demo.initializer.AfterHelloApplicationContextInitializer
这时候,启动Spring Boot项目,会发现控制台在打印Banner后就执行了这两个初始化器,并且HelloApplicationContextInitializer的initialize方法执行时机先于AfterHelloApplicationContextInitializer的initialize方法:
2.4 加载应用事件监听器
在加载完应用上下文初始器后,下一行的setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));代码加载了应用事件监听器。与加载事件上下文初始器类似,Spring Boot也是通过Spring的工厂方法来实例化ApplicationListener的实现类,并进行排序。
既然是事件监听,那么其可以监听什么事件呢?其监听的是ApplicationEvent接口的实现类,我们查看一下都有哪些事件实现了这个接口:
这里我们以ContextClosedEvent为例子来编写自定义的应用事件监听器,监听Spring上下文关闭事件。
在com.allan.demo下新建listener包,然后创建一个ContextClosedEventListener类,实现ApplicationListener接口:
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ContextClosedEventListener implements ApplicationListener<ContextClosedEvent> {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("ContextClosedEvent: " + event.getApplicationContext().getId());
}
}
上面代码实现了对ContextClosedEvent事件的监听,并且分配了最高优先级。
接着创建一个优先级比ContextClosedEventListener低的上面代码实现了对ContextClosedEvent事件监听器AfterContextClosedEventListener:
public class AfterContextClosedEventListener implements ApplicationListener<ContextClosedEvent>, Ordered {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("AfterContextClosedEventr: " + event.getApplicationContext().getId());
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
}
最后,别忘了在Spring工厂配置文件里进行配置:
# Application Listeners
org.springframework.context.ApplicationListener=\
com.allan.demo.listener.ContextClosedEventListener,\
com.allan.demo.listener.AfterContextClosedEventListener
在Spring Boot入口类中将环境指定为非WEB环境(这样在启动后应用会马上关闭):
new SpringApplicationBuilder(DemoApplication.class)
.web(WebApplicationType.NONE)
.run(args);
运行Spring Boot入口类,控制台输出如下:
2.5 推断入口类
接着构造器里的代码下一行this.mainApplicationClass = deduceMainApplicationClass();用于推断运行Spring Boot应用的入口类。查看deduceMainApplicationClass方法源码:
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
代码主要逻辑是根据Main线程执行堆栈判断实际的入口类。
准备阶段介绍完毕后,接下来开始介绍运行阶段。
3.SpringApplication运行阶段
SpringApplication的运行阶段对应SpringApplication的run方法,我们查看其源码:
public ConfigurableApplicationContext run(String... args) {
//1.开启时间监听
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//2.初始化应用上下文和异常报告集合
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//3.设置系统属性 `java.awt.headless` 的值,默认值为:true
configureHeadlessProperty();
//4.开启运行监听器并发布应用启动事件
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
//5.初始化默认应用参数类
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 6.根据运行监听器和应用参数来准备 Spring 环境(创建 Environment)
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
// 7.创建 Banner 打印类
Banner printedBanner = printBanner(environment);
// 8.创建应用上下文(创建Context)
context = createApplicationContext();
// 9.准备异常报告器
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 10、准备应用上下文(装配Context)
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 11、刷新应用上下文(Refresh Context)
refreshContext(context);
// 12、应用上下文刷新后置处理
afterRefresh(context, applicationArguments);
// 13、停止计时监控类
stopWatch.stop();
// 14、输出日志记录执行主类名、时间信息
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 15、发布应用上下文启动完成事件(广播应用已启动)
listeners.started(context);
// 16、执行所有 Runner 运行器(执行Runner)
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
// 17、发布应用上下文就绪事件(广播应用运行中)
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
// 18、返回应用上下文
return context;
}
3.1 开启时间监听
run方法开头的这两行代码用于开启时间监听:
StopWatch stopWatch = new StopWatch();
stopWatch.start();
这个计时监控类 StopWatch 的start方法相关源码:
public void start() throws IllegalStateException {
this.start("");
}
public void start(String taskName) throws IllegalStateException {
if (this.currentTaskName != null) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
} else {
this.currentTaskName = taskName;
this.startTimeMillis = System.currentTimeMillis();
}
}
首先记录了当前任务的名称,默认为空字符串,然后记录当前 Spring Boot 应用启动的开始时间。上面代码用于开启Spring Boot应用启动时间监听,配合下面的stopWatch.stop();便可以计算出完整的启动时间。
3.2 初始化应用上下文和异常报告集合
源码为:
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
3.3 设置系统属性 java.awt.headless 的值
源码为:
configureHeadlessProperty();
设置该默认值为:true,Java.awt.headless = true 有什么作用?
对于一个 Java 服务器来说经常要处理一些图形元素,例如地图的创建或者图形和图表等。这些API基本上总是需要运行一个X-server以便能使用AWT(Abstract Window Toolkit,抽象窗口工具集)。然而运行一个不必要的 X-server 并不是一种好的管理方式。有时你甚至不能运行 X-server,因此最好的方案是运行 headless 服务器,来进行简单的图像处理。参考:www.cnblogs.com/princessd8251/p/4000016.html
3.4 开启运行监听器
run方法的这几行代码用于加载Spring应用运行监听器(SpringApplicationRunListener):
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
getRunListeners方法源码:
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}
SpringApplicationRunListeners(Log log, Collection<? extends SpringApplicationRunListener> listeners) {
this.log = log;
this.listeners = new ArrayList<>(listeners);
}
上面代码通过SpringFactoriesLoader检索META-INF/spring.factories找到声明的所有SpringApplicationRunListener的实现类并将其实例化,然后装配到List运行监听器集合中。
listeners.started();用于遍历运行监听器集合中的所有SpringApplicationRunListener的实现类,并逐一调用它们的starting方法,广播Spring Boot应用要开始启动了。
在Spring Boot中SpringApplicationRunListener接口用于监听整个Spring Boot应用生命周期,其代码如下所示:
public interface SpringApplicationRunListener {
void starting();
void environmentPrepared(ConfigurableEnvironment environment);
void contextPrepared(ConfigurableApplicationContext context);
void contextLoaded(ConfigurableApplicationContext context);
void started(ConfigurableApplicationContext context);
void running(ConfigurableApplicationContext context);
void failed(ConfigurableApplicationContext context, Throwable exception);
}
这些方法对应着Spring Boot应用生命周期的各个阶段:
我们在com.allan.demo.linstener下自定义一个SpringApplicationRunListener接口实现类HelloSpringApplicationRunListener:
public class HelloApplicationRunListener implements SpringApplicationRunListener {
public HelloApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting() {
System.out.println("HelloApplicationRunListener starting......");
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
}
@Override
public void started(ConfigurableApplicationContext context) {
}
@Override
public void running(ConfigurableApplicationContext context) {
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
}
}
通过这个实现类,我们可以在Spring Boot应用刚启动的时候在控制台输出HelloApplicationRunListener starting…。
因为其基于Spring的工厂方法来实现,所以我们需要在spring.factories文件里配置这个实现类:
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
com.allan.demo.run.HelloApplicationRunListener
启动Spring Boot应用便可以在控制台看到如下输出了:
3.5 初始化默认应用参数类
源码如下:
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
3.6 创建 Environment
run方法中的这行代码用于创建并配置当前SpringBoot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile):
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
我们已经在准备阶段里推断出了应用类型,这里只要根据相应的应用类型来创建相应的应用环境即可,类型和环境对应关系如下:
-
Web Reactive: StandardReactiveWebEnvironment
-
Web Servlet: StandardServletEnvironment
-
非 Web: StandardEnvironment
在prepareEnvironment方法中会执行listeners.environmentPrepared(environment);,用于遍历调用所有SpringApplicationRunListener实现类的environmentPrepared()方法,广播Environment准备完毕。
准备环境的 prepareEnvironment 源码:
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
// 6.1 获取(或者创建)应用环境
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 6.2 配置应用环境
configureEnvironment(environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach(environment);
listeners.environmentPrepared(environment);
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
6.1 获取(或者创建)应用环境
源码为:
private ConfigurableEnvironment getOrCreateEnvironment() {
if (this.environment != null) {
return this.environment;
}
switch (this.webApplicationType) {
case SERVLET:
return new StandardServletEnvironment();
case REACTIVE:
return new StandardReactiveWebEnvironment();
default:
return new StandardEnvironment();
}
}
这里分为标准 Servlet 环境和标准环境。
6.2 配置应用环境
源码为:
protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
if (this.addConversionService) {
ConversionService conversionService = ApplicationConversionService.getSharedInstance();
environment.setConversionService((ConfigurableConversionService) conversionService);
}
configurePropertySources(environment, args);
configureProfiles(environment, args);
}
这里分为以下两步来配置应用环境。
- 配置 property sources
- 配置 Profiles
这里主要处理所有 property sources 配置和 profiles 配置。
3.7 是否打印Banner
run方法中的这行代码会根据我们的配置来决定是否打印Banner:
Banner printedBanner = printBanner(environment);
3.8 创建Context
run方法中的这行代码用于创建ApplicationContext:
context = createApplicationContext();
createApplicationContext() 方法的源码:
public static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context."
+ "annotation.AnnotationConfigApplicationContext";
public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
+ "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
+ "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
其实就是根据不同的应用类型初始化不同的上下文应用类。
不同的环境对应不同的ApplicationContext:
-
Web Reactive: AnnotationConfigReactiveWebServerApplicationContext
-
Web Servlet: AnnotationConfigServletWebServerApplicationContext
-
非 Web: AnnotationConfigApplicationContext
3.9 准备异常报告器
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
调用的是 getSpringFactoriesInstances 方法来获取配置的异常类名称并实例化所有的异常处理类。
该异常报告处理类配置在 spring-boot-2.1.8.RELEASE.jar!/META-INF/spring.factories 这个配置文件里面。
# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=\
org.springframework.boot.diagnostics.FailureAnalyzers
3.10 装配Context
run方法中的这行代码用于装配Context:
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
方法prepareContext的源码如下所示:
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//10.1 绑定环境到上下文
context.setEnvironment(environment);
// 10.2 配置上下文的 bean 生成器及资源加载器
postProcessApplicationContext(context);
// 10.3 为上下文应用所有初始化器
applyInitializers(context);
// 10.4 触发所有 SpringApplicationRunListener 监听器的 contextPrepared 事件方法
listeners.contextPrepared(context);
// 10.5 记录启动日志
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
// 10.6 注册两个特殊的单例bean
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// Load the sources
// 10.7 加载所有资源
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
// 10.8 触发所有 SpringApplicationRunListener 监听器的 contextLoaded 事件方法
listeners.contextLoaded(context);
}
总结:prepareContext方法开头为ApplicationContext加载了environment,之后通过applyInitializers方法逐个执行ApplicationContextInitializer的initialize方法来进一步封装ApplicationContext,并调用所有的SpringApplicationRunListener实现类的contextPrepared方法,广播ApplicationContext已经准备完毕了。
之后初始化IOC容器,并调用SpringApplicationRunListener实现类的contextLoaded方法,广播ApplicationContext加载完成,这里就包括通过@EnableAutoConfiguration导入的各种自动配置类。
3.11 Refresh Context
run方法中的这行代码用于初始化所有自动配置类,并调用ApplicationContext的refresh方法:
refreshContext(context);
这个主要是刷新 Spring 的应用上下文,源码如下:
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
3.12 应用上下文刷新后置处理
源码为:
afterRefresh(context, applicationArguments);
这个方法的源码是空的,目前可以做一些自定义的后置处理操作。
/**
* Called after the context has been refreshed.
* @param context the application context
* @param args the application arguments
*/
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}
3.13 停止计时监控类
stopWatch.stop();
public void stop() throws IllegalStateException {
if (this.currentTaskName == null) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
} else {
long lastTime = System.currentTimeMillis() - this.startTimeMillis;
this.totalTimeMillis += lastTime;
this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) {
this.taskList.add(this.lastTaskInfo);
}
++this.taskCount;
this.currentTaskName = null;
}
}
3.14 输出日志记录执行主类名、时间信息
源码为:
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
3.15 广播应用已启动
run方法中的这行代码用于广播Spring Boot应用已启动:
listeners.started(context);
started方法会调用所有的SpringApplicationRunListener的finished方法,广播SpringBoot应用已经成功启动。
3.16 执行Runner
执行所有 Runner 运行器。
callRunners(context, applicationArguments);
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) {
//遍历所有ApplicationRunner和CommandLineRunner的实现类,并执行其run方法
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
callRunner 源码如下:
private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
try {
(runner).run(args);
}
catch (Exception ex) {
throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
}
}
private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
try {
(runner).run(args.getSourceArgs());
}
catch (Exception ex) {
throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
}
}
从这段代码中可以看出执行所有 ApplicationRunner 和 CommandLineRunner 这两种运行器的实现类,并执行其run方法。
我们可以实现自己的ApplicationRunner或者CommandLineRunner,来对Spring Boot的启动过程进行扩展。
我们在com.allan.demo下新建runner包,然后创建一个ApplicationRunner的实现类HelloApplicationRunner:
@Component
public class HelloApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("HelloApplicationRunner: hello spring boot");
}
}
这里我们需要将HelloApplicationRunner使用@Component注解标注,让其注册到IOC容器中。
然后再创建一个CommandLineRunner的实现类HelloCommandLineRunner:
@Component
public class HelloCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("HelloCommandLineRunner: hello spring boot");
}
}
启动Spring Boot应用,便可以在应用刚启动好后看到如下输出:
3.17 广播应用运行中
listeners.running(context);
用于调用SpringApplicationRunListener的running方法(触发所有 SpringApplicationRunListener 监听器的 running 事件方法),广播Spring Boot应用正在运行中。
当run方法运行出现异常时,便会调用handleRunFailure方法来处理异常,该方法里会通过listeners.failed(context, exception);来调用SpringApplicationRunListener的failed方法,广播应用启动失败,并将异常扩散出去。
PS:上面所有的广播事件都是使用Spring的应用事件广播器接口ApplicationEventMulticaster的实现类SimpleApplicationEventMulticaster来进行广播的。3.18 返回应用上下文
源码:
return context;