Support default profile (SPR-7508, SPR-7778)

'default' is now a reserved profile name, indicating
that any beans defined within that profile will be registered
unless another profile or profiles have been activated.

Examples below are expressed in XML, but apply equally when
using the @Profile annotation.

EXAMPLE 1:

        <beans>
            <beans profile="default">
                <bean id="foo" class="com.acme.EmbeddedFooImpl"/>
            </beans>
            <beans profile="production">
                <bean id="foo" class="com.acme.ProdFooImpl"/>
            </beans>
        </beans>

    In the case above, the EmbeddedFooImpl 'foo' bean will be
    registered if:
        a) no profile is active
        b) the 'default' profile has explicitly been made active

    The ProdFooImpl 'foo' bean will be registered if the 'production'
    profile is active.

EXAMPLE 2:

        <beans profile="default,xyz">
            <bean id="foo" class="java.lang.String"/>
        </beans>

    Bean 'foo' will be registered if any of the following are true:
        a) no profile is active
        b) 'xyz' profile is active
        c) 'default' profile has explicitly been made active
        d) both (b) and (c) are true

Note that the default profile is not to be confused with specifying no
profile at all.  When the default profile is specified, beans are
registered only if no other profiles are active; whereas when no profile
is specified, bean definitions are always registered regardless of which
profiles are active.

The default profile may be configured programmatically:

    environmnent.setDefaultProfile("embedded");

or declaratively through any registered PropertySource, e.g. system properties:

    -DdefaultSpringProfile=embedded

Assuming either of the above, example 1 could be rewritten as follows:

        <beans>
            <beans profile="embedded">
                <bean id="foo" class="com.acme.EmbeddedFooImpl"/>
            </beans>
            <beans profile="production">
                <bean id="foo" class="com.acme.ProdFooImpl"/>
            </beans>
        </beans>

It is unlikely that use of the default profile will make sense in
conjunction with a statically specified 'springProfiles' property.
For example, if 'springProfiles' is specified as a web.xml context
param, that profile will always be active for that application,
negating the possibility of default profile bean definitions ever
being registered.

The default profile is most useful for ensuring that a valid set of
bean definitions will always be registered without forcing users
to explictly specify active profiles.  In the embedded vs. production
examples above, it is assumed that the application JVM will be started
with -DspringProfiles=production when the application is in fact in
a production environment.  Otherwise, the embedded/default profile bean
definitions will always be registered.
This commit is contained in:
Chris Beams
2010-12-01 09:01:58 +00:00
parent b33da670e5
commit 5062dc31af
15 changed files with 249 additions and 129 deletions

View File

@@ -50,7 +50,17 @@ import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
*/
public abstract class AbstractEnvironment implements ConfigurableEnvironment {
public static final String SPRING_PROFILES_PROPERTY_NAME = "springProfiles";
public static final String ACTIVE_PROFILES_PROPERTY_NAME = "springProfiles";
public static final String DEFAULT_PROFILE_PROPERTY_NAME = "defaultSpringProfile";
/**
* Default name of the default profile. Override with
* {@link #setDefaultProfile(String)}.
*
* @see #setDefaultProfile(String)
*/
public static final String DEFAULT_PROFILE_NAME = "default";
protected final Log logger = LogFactory.getLog(getClass());
@@ -66,6 +76,8 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment {
private boolean explicitlySetProfiles;
private String defaultProfile = DEFAULT_PROFILE_NAME;
public void addPropertySource(PropertySource<?> propertySource) {
propertySources.push(propertySource);
@@ -183,7 +195,7 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment {
if (explicitlySetProfiles)
return;
String profiles = getProperty(SPRING_PROFILES_PROPERTY_NAME);
String profiles = getProperty(ACTIVE_PROFILES_PROPERTY_NAME);
if (profiles == null || profiles.equals("")) {
return;
}
@@ -267,6 +279,31 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment {
return doResolvePlaceholders(text, strictHelper);
}
public boolean acceptsProfiles(String[] specifiedProfiles) {
boolean activeProfileFound = false;
Set<String> activeProfiles = this.getActiveProfiles();
for (String profile : specifiedProfiles) {
if (activeProfiles.contains(profile)
|| (activeProfiles.isEmpty() && profile.equals(this.getDefaultProfile()))) {
activeProfileFound = true;
break;
}
}
return activeProfileFound;
}
public String getDefaultProfile() {
String defaultSpringProfileProperty = getProperty(DEFAULT_PROFILE_PROPERTY_NAME);
if (defaultSpringProfileProperty != null) {
return defaultSpringProfileProperty;
}
return defaultProfile;
}
public void setDefaultProfile(String defaultProfile) {
this.defaultProfile = defaultProfile;
}
private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
return helper.replacePlaceholders(text, new PlaceholderResolver() {
public String resolvePlaceholder(String placeholderName) {

View File

@@ -29,4 +29,11 @@ public interface ConfigurableEnvironment extends Environment, PropertySourceAggr
*/
void setActiveProfiles(String... profiles);
/**
* Set the default profile name to be used instead of 'default'
*
* @param defaultProfile
*/
void setDefaultProfile(String defaultProfile);
}

View File

@@ -35,6 +35,19 @@ public interface Environment {
*/
Set<String> getActiveProfiles();
/**
* TODO SPR-7508: document
*/
String getDefaultProfile();
/**
* TODO SPR-7508: document
* returns true if:
* a) one or more of specifiedProfiles are active in the given environment - see {@link #getActiveProfiles()}
* b) specifiedProfiles contains default profile - see {@link #getDefaultProfile()}
*/
boolean acceptsProfiles(String[] specifiedProfiles);
/**
* TODO SPR-7508: document
*/

View File

@@ -28,10 +28,11 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.matchers.JUnitMatchers.hasItem;
import static org.junit.matchers.JUnitMatchers.hasItems;
import static org.springframework.core.env.AbstractEnvironment.SPRING_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILE_NAME;
import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILE_PROPERTY_NAME;
import static org.springframework.core.env.DefaultEnvironmentTests.CollectionMatchers.isEmpty;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.AccessControlException;
import java.security.Permission;
@@ -48,8 +49,6 @@ import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.internal.matchers.TypeSafeMatcher;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
/**
* Unit tests for {@link DefaultEnvironment}.
@@ -220,59 +219,47 @@ public class DefaultEnvironmentTests {
public void systemPropertiesEmpty() {
assertThat(environment.getActiveProfiles(), isEmpty());
System.setProperty(SPRING_PROFILES_PROPERTY_NAME, "");
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "");
assertThat(environment.getActiveProfiles(), isEmpty());
System.getProperties().remove(SPRING_PROFILES_PROPERTY_NAME);
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
public void systemPropertiesResoloutionOfProfiles() {
assertThat(environment.getActiveProfiles(), isEmpty());
System.setProperty(SPRING_PROFILES_PROPERTY_NAME, "foo");
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo");
assertThat(environment.getActiveProfiles(), hasItem("foo"));
// clean up
System.getProperties().remove(SPRING_PROFILES_PROPERTY_NAME);
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
public void systemPropertiesResoloutionOfMultipleProfiles() {
assertThat(environment.getActiveProfiles(), isEmpty());
System.setProperty(SPRING_PROFILES_PROPERTY_NAME, "foo,bar");
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar");
assertThat(environment.getActiveProfiles(), hasItems("foo", "bar"));
System.setProperty(SPRING_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace
assertThat(environment.getActiveProfiles(), not(hasItems("foo", "bar")));
assertThat(environment.getActiveProfiles(), hasItems("bar", "baz"));
System.getProperties().remove(SPRING_PROFILES_PROPERTY_NAME);
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
/*
static class WithNoProfile { }
@Profile("test")
static class WithTestProfile { }
@Test
public void accepts() throws IOException {
assertThat(environment.accepts(metadataForClass(WithNoProfile.class)), is(true));
assertThat(environment.accepts(metadataForClass(WithTestProfile.class)), is(false));
assertThat(environment.accepts("foo,bar"), is(false));
assertThat(environment.accepts("test"), is(false));
assertThat(environment.accepts("test,foo"), is(false));
environment.setActiveProfiles("test");
assertThat(environment.accepts(metadataForClass(WithNoProfile.class)), is(true));
assertThat(environment.accepts(metadataForClass(WithTestProfile.class)), is(true));
assertThat(environment.accepts("foo,bar"), is(false));
assertThat(environment.accepts("test"), is(true));
assertThat(environment.accepts("test,foo"), is(true));
public void environmentResolutionOfDefaultSpringProfileProperty_noneSet() {
assertThat(environment.getDefaultProfile(), equalTo(DEFAULT_PROFILE_NAME));
}
@Test
public void environmentResolutionOfDefaultSpringProfileProperty_isSet() {
testProperties.setProperty(DEFAULT_PROFILE_PROPERTY_NAME, "custom-default");
assertThat(environment.getDefaultProfile(), equalTo("custom-default"));
}
*/
@Test
public void systemPropertiesAccess() {
@@ -413,10 +400,6 @@ public class DefaultEnvironmentTests {
}
}
private AnnotationMetadata metadataForClass(Class<?> clazz) throws IOException {
return new SimpleMetadataReaderFactory().getMetadataReader(clazz.getName()).getAnnotationMetadata();
}
public static class CollectionMatchers {
public static Matcher<Collection<?>> isEmpty() {