最近看了下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里。
鉴于springCloudConfig是使用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。