欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot环境变量(environment)加载源码分析

程序员文章站 2022-04-22 10:33:44
...

代码入口

//SpringApplication run 环境变量初始化入口
prepareEnvironment(listeners, bootstrapContext, applicationArguments)

//prepareEnvironment 分步加载环境变量
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
			DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
		//创建和初始化-环境变量对象
		ConfigurableEnvironment environment = getOrCreateEnvironment();
		
		configureEnvironment(environment, applicationArguments.getSourceArgs());
		ConfigurationPropertySources.attach(environment);
		listeners.environmentPrepared(bootstrapContext, environment);
		DefaultPropertiesPropertySource.moveToEnd(environment);
		configureAdditionalProfiles(environment);
		bindToSpringApplication(environment);
		if (!this.isCustomEnvironment) {
			environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
					deduceEnvironmentClass());
		}
		ConfigurationPropertySources.attach(environment);
		return environment;
	}

创建和初始化-环境变量对象

//根据应用类型不同,创建不同的环境变量对象
//环境变量的来源属性值来源不同,内部有许多(List)PropertySource,分别保存
private ConfigurableEnvironment getOrCreateEnvironment() {
		if (this.environment != null) {
			return this.environment;
		}
		switch (this.webApplicationType) {
		case SERVLET:
		    //web应用环境变量类型
		    //加载systemProperties,systemEnvironment
		    //加载servletConfigInitParams,servletContextInitParams
			return new StandardServletEnvironment();
		case REACTIVE:
		    //响应应用环境变量类型
			return new StandardReactiveWebEnvironment();
		default:
		    //只是启动一个容器的应用
		    //加载systemProperties,systemEnvironment
			return new StandardEnvironment();
		}
	}
	
1.StandardEnvironment加载一些系统环境变量参数即可
2.StandardServletEnvironment是一个web应用,自然还有一些web相关的环境变量参数