Allow spring.profiles.include to be used anywhere to add active profiles

Previously, spring.profiles.include was only considered when it was
used in a configuration file. It was ignored in any other property
source.

This commit updates ConfigFileApplicationListener so that
spring.profiles.include can be used in any property source to add to
the profiles that have been declared active via
spring.profiles.active.

Closes gh-7668
This commit is contained in:
Andy Wilkinson 2017-01-23 11:16:17 +00:00
parent 07d9c3fef6
commit 393cfe505e
2 changed files with 17 additions and 2 deletions

View File

@ -393,8 +393,11 @@ public class ConfigFileApplicationListener implements EnvironmentPostProcessor,
} }
// Any pre-existing active profiles set via property sources (e.g. System // Any pre-existing active profiles set via property sources (e.g. System
// properties) take precedence over those added in config files. // properties) take precedence over those added in config files.
Set<Profile> activeProfiles = bindSpringProfiles( SpringProfiles springProfiles = bindSpringProfiles(
this.environment.getPropertySources()).getActiveProfiles(); this.environment.getPropertySources());
Set<Profile> activeProfiles = new LinkedHashSet<Profile>(
springProfiles.getActiveProfiles());
activeProfiles.addAll(springProfiles.getIncludeProfiles());
maybeActivateProfiles(activeProfiles); maybeActivateProfiles(activeProfiles);
return activeProfiles; return activeProfiles;
} }

View File

@ -837,6 +837,18 @@ public class ConfigFileApplicationListenerTests {
assertThat(environment.acceptsProfiles("customdefault")).isTrue(); assertThat(environment.acceptsProfiles("customdefault")).isTrue();
} }
@Test
public void additionalProfilesCanBeIncludedFromAnyPropertySource() throws Exception {
SpringApplication application = new SpringApplication(Config.class);
application.setWebEnvironment(false);
this.context = application.run("--spring.profiles.active=myprofile",
"--spring.profiles.include=dev");
String property = this.context.getEnvironment().getProperty("my.property");
assertThat(property).isEqualTo("fromdevpropertiesfile");
assertThat(this.context.getEnvironment().containsProperty("customdefault"))
.isFalse();
}
private Condition<ConfigurableEnvironment> matchingPropertySource( private Condition<ConfigurableEnvironment> matchingPropertySource(
final String sourceName) { final String sourceName) {
return new Condition<ConfigurableEnvironment>( return new Condition<ConfigurableEnvironment>(