springboot获取active_springboot的spring.profiles.active配置

最近看了下spring.profiles.active配置的作用,我们在默认的配置文件application.yml配置了spring.profiles.active:dev属性,在SpringApplication的prepareEnvironment方法里,会用SpringApplicationRunListeners发ApplicationEnvironmentPreparedEvent事件,ConfigFileApplicationListener会监听这个消息,内部会委派调用Loader.load()方法。

public void load() throws IOException {

this.propertiesLoader = new PropertySourcesLoader();

this.activatedProfiles = false;

this.profiles = Collections.asLifoQueue(new

LinkedList());

this.processedProfiles = new

LinkedList();

// Pre-existing active profiles set via

Environment.setActiveProfiles()

// are additional profiles and config files are allowed to add

more if

// they want to, so don't call

addActiveProfiles() here.

Set initialActiveProfiles

= initializeActiveProfiles();

this.profiles.addAll(getUnprocessedActiveProfiles(initialActiveProfiles));

if (this.profiles.isEmpty()) {

for (String defaultProfileName :

this.environment.getDefaultProfiles()) {

Profile defaultProfile = new Profile(defaultProfileName,

true);

if (!this.profiles.contains(defaultProfile)) {

this.profiles.add(defaultProfile);

}

}

}

// The default profile for these purposes is represented as

null. We add it

// last so that it is first out of the queue (active profiles

will then

// override any settings in the defaults when the list is

reversed later).

this.profiles.add(null);

while (!this.profiles.isEmpty()) {

Profile profile = this.profiles.poll();

for (String location : getSearchLocations()) {

if (!location.endsWith("/"))

{

// location is a filename already, so don't

search for more

// filenames

load(location, null, profile);

}

else {

for (String name : getSearchNames()) {

load(location, name, profile);

}

}

}

this.processedProfiles.add(profile);

}

addConfigurationProperties(this.propertiesLoader.getPropertySources());

}

​1.获取当前的ActiveProfiles,若是没有使用default

profile

2.往profiles​集合里新增一个null(读取默认配置比如application.yml)

3.循环从SearchLocations​,SearchNames,AllFileExtensions拼接,读取配置文件

如果存在​spring.profiles.active配置,设置到profiles集合里,并且设置到ConfigurableEnvironment的ActiveProfiles属性里,然后从profiles移除DefaultProfiles

4.如此循环解析完所有配置,取出读取到的配置放到ConfigurableEnvironment​里。

鉴于springCloud​Config是使用ConfigClientProperties配置类获取url的,它的构造方法如下:

public ConfigClientProperties(Environment environment) {

String[] profiles = environment.getActiveProfiles();

if (profiles.length == 0) {

profiles = environment.getDefaultProfiles();

}

this.setProfile(StringUtils.arrayToCommaDelimitedString(profiles));

}

所以spring.profiles.active​属性也能决定读取配置中心的profile。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值