SpringBoot版本:2.1.1 ==》启动流程分析汇总
接上篇博客 Spring Boot 2.1.1(九)启动流程分析之args参数的封装解析。
目录
3、发布ApplicationEnvironmentPreparedEvent事件
args参数封装执行完成以后,就是构建环境Environment,下面分析其运行流程。
public ConfigurableApplicationContext run(String... args) {
....
try {
//本篇内容从本行开始记录
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
//本篇内容记录到这,后续更新
....
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
}
构建环境
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
//创建环境,这里是根据web应用类型返回的,得到的是一个标准基于servlet的web环境
ConfigurableEnvironment environment = getOrCreateEnvironment();
//配置环境,参数是上一步创建的environment和原始args参数
configureEnvironment(environment, applicationArguments.getSourceArgs());
//发布事件ApplicationEnvironmentPreparedEvent
listeners.environmentPrepared(environment);
//将spring.main配置绑定到SpringApplication
bindToSpringApplication(environment);
//isCustomEnvironment默认为false,如果你通过SpringApplication对象的setEnvironment()方法设置了环境,该值变为true,直接跳过这里
//转换为标准环境
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
1、创建ConfigurableEnvironment对象
private ConfigurableEnvironment getOrCreateEnvironment() {
//如果你通过SpringApplication对象的setEnvironment()方法设置了环境,则直接返回该环境
if (this.environment != null) {
return this.environment;
}
//根据webApplicationType选择
switch (this.webApplicationType) {
case SERVLET:
//标准的servlet环境
return new StandardServletEnvironment();
case REACTIVE:
//标准的响应式web环境
return new StandardReactiveWebEnvironment();
default:
//标准环境
return new StandardEnvironment();
}
}
返回的标准servlet环境如下:
StandardServletEnvironment {
activeProfiles=[],
defaultProfiles=[default],
propertySources[
StubPropertySource{name='servletConfigInitParams'},
StubPropertySource {name='servletContextInitParams'},
MapPropertySource {name='systemProperties'},
SystemEnvironmentPropertySource {name='systemEnvironment'}]
}