Set environment active profiles according to processing order

Fixes gh-13965
pull/14003/head
Madhura Bhave 6 years ago
parent e4442f4b14
commit 7e2494ebdd

@ -337,6 +337,7 @@ public class ConfigFileApplicationListener
addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}
resetEnvironmentProfiles(this.processedProfiles);
load(null, this::getNegativeProfileFilter,
addToLoaded(MutablePropertySources::addFirst, true));
addLoadedPropertySources();
@ -673,6 +674,21 @@ public class ConfigFileApplicationListener
return new LinkedHashSet<>(list);
}
/**
* This ensures that the order of active profiles in the {@link Environment}
* matches the order in which the profiles were processed.
* @param processedProfiles the processed profiles
*/
private void resetEnvironmentProfiles(List<Profile> processedProfiles) {
String[] names = processedProfiles.stream().filter((profile) -> {
if (profile != null && !profile.isDefaultProfile()) {
return true;
}
return false;
}).map(Profile::getName).toArray(String[]::new);
this.environment.setActiveProfiles(names);
}
private void addLoadedPropertySources() {
MutablePropertySources destination = this.environment.getPropertySources();
List<MutablePropertySources> loaded = new ArrayList<>(this.loaded.values());

@ -406,7 +406,7 @@ public class ConfigFileApplicationListenerTests {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment,
"spring.profiles.active=dev", "spring.profiles.include=other");
this.initializer.postProcessEnvironment(this.environment, this.application);
assertThat(this.environment.getActiveProfiles()).contains("dev", "other");
assertThat(this.environment.getActiveProfiles()).containsExactly("other", "dev");
assertThat(this.environment.getProperty("my.property"))
.isEqualTo("fromdevpropertiesfile");
validateProfilePrecedence(null, "other", "dev");

@ -116,6 +116,20 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests {
assertThat(this.context.getEnvironment().getProperty("not-e")).isNull();
}
@Test
public void yamlProfileCascadingMultipleActiveProfilesViaPropertiesShouldPreserveOrder() {
SpringApplication application = new SpringApplication(Config.class);
application.setWebApplicationType(WebApplicationType.NONE);
String configName = "--spring.config.name=cascadingprofiles";
this.context = application.run(configName, "--spring.profiles.active=A,B");
assertVersionProperty(this.context, "D", "A", "C", "E", "B", "D");
assertThat(this.context.getEnvironment().getProperty("not-a")).isNull();
assertThat(this.context.getEnvironment().getProperty("not-b")).isNull();
assertThat(this.context.getEnvironment().getProperty("not-c")).isNull();
assertThat(this.context.getEnvironment().getProperty("not-d")).isNull();
assertThat(this.context.getEnvironment().getProperty("not-e")).isNull();
}
@Test
public void yamlProfileCascadingOverrideProfilesB() {
SpringApplication application = new SpringApplication(Config.class);

Loading…
Cancel
Save