SpringBoot(十)启动流程分析之ApplicationEnvironmentPreparedEvent事件发布

本文分析了SpringBoot启动过程中构建环境的流程,重点讲解了ApplicationEnvironmentPreparedEvent事件的发布,包括配置属性源、配置文件、EnvironmentPostProcessor的执行等,这些步骤涉及配置文件加载、日志系统初始化等关键操作。
摘要由CSDN通过智能技术生成

SpringBoot版本:2.1.1   ==》启动流程分析汇总

接上篇博客 Spring Boot 2.1.1(九)启动流程分析之args参数的封装解析

目录

构建环境

1、创建ConfigurableEnvironment对象

2、配置环境

2.1、配置属性源

2.2、配置配置文件

3、发布ApplicationEnvironmentPreparedEvent事件

 4、将环境绑定到SpringApplication

 5、将配置属性源绑定到Environment

 总结


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'}]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值