Class AbstractEnvironment
- All Implemented Interfaces:
ConfigurableEnvironment
,ConfigurablePropertyResolver
,Environment
,PropertyResolver
- Direct Known Subclasses:
MockEnvironment
,StandardEnvironment
Environment
implementations. Supports the notion of
reserved default profile names and enables specifying active and default profiles
through the ACTIVE_PROFILES_PROPERTY_NAME
and
DEFAULT_PROFILES_PROPERTY_NAME
properties.
Concrete subclasses differ primarily on which PropertySource
objects they
add by default. AbstractEnvironment
adds none. Subclasses should contribute
property sources through the protected customizePropertySources(MutablePropertySources)
hook, while clients should customize using ConfigurableEnvironment.getPropertySources()
and working against the MutablePropertySources
API.
See ConfigurableEnvironment
javadoc for usage examples.
- Since:
- 3.1
- Author:
- Chris Beams, Juergen Hoeller, Phillip Webb
- See Also:
-
Field Summary
Modifier and TypeFieldDescriptionstatic final String
Name of the property to set to specify active profiles: "spring.profiles.active".static final String
Name of the property to set to specify profiles that are active by default: "spring.profiles.default".static final String
System property that instructs Spring to ignore system environment variables, i.e.protected final Log
static final String
Name of the reserved default profile name: "default". -
Constructor Summary
ModifierConstructorDescriptionCreate a newEnvironment
instance, calling back tocustomizePropertySources(MutablePropertySources)
during construction to allow subclasses to contribute or manipulatePropertySource
instances as appropriate.protected
AbstractEnvironment
(MutablePropertySources propertySources) Create a newEnvironment
instance with a specificMutablePropertySources
instance, calling back tocustomizePropertySources(MutablePropertySources)
during construction to allow subclasses to contribute or manipulatePropertySource
instances as appropriate. -
Method Summary
Modifier and TypeMethodDescriptionboolean
acceptsProfiles
(String... profiles) Deprecated.boolean
acceptsProfiles
(Profiles profiles) Determine whether the givenProfiles
predicate matches the active profiles — or in the case of no explicit active profiles, whether the givenProfiles
predicate matches the default profiles.void
addActiveProfile
(String profile) Add a profile to the current set of active profiles.boolean
containsProperty
(String key) Return whether the given property key is available for resolution, i.e.protected ConfigurablePropertyResolver
createPropertyResolver
(MutablePropertySources propertySources) Factory method used to create theConfigurablePropertyResolver
instance used by the Environment.protected void
customizePropertySources
(MutablePropertySources propertySources) Customize the set ofPropertySource
objects to be searched by thisEnvironment
during calls togetProperty(String)
and related methods.Return the set of active profiles as explicitly set throughsetActiveProfiles(java.lang.String...)
or if the current set of active profiles is empty, check for the presence ofdoGetActiveProfilesProperty()
and assign its value to the set of active profiles.protected String
Return the property value for the active profiles.Return the set of default profiles explicitly set viasetDefaultProfiles(String...)
or if the current set of default profiles consists only of reserved default profiles, then check for the presence ofdoGetActiveProfilesProperty()
and assign its value (if any) to the set of default profiles.protected String
Return the property value for the default profiles.String[]
Return the set of profiles explicitly made active for this environment.Return theConfigurableConversionService
used when performing type conversions on properties.String[]
Return the set of profiles to be active by default when no active profiles have been set explicitly.getProperty
(String key) Return the property value associated with the given key, ornull
if the key cannot be resolved.<T> T
getProperty
(String key, Class<T> targetType) Return the property value associated with the given key, ornull
if the key cannot be resolved.<T> T
getProperty
(String key, Class<T> targetType, T defaultValue) Return the property value associated with the given key, ordefaultValue
if the key cannot be resolved.getProperty
(String key, String defaultValue) Return the property value associated with the given key, ordefaultValue
if the key cannot be resolved.protected final ConfigurablePropertyResolver
Return theConfigurablePropertyResolver
being used by theEnvironment
.Return thePropertySources
for thisEnvironment
in mutable form, allowing for manipulation of the set ofPropertySource
objects that should be searched when resolving properties against thisEnvironment
object.Return the property value associated with the given key (nevernull
).<T> T
getRequiredProperty
(String key, Class<T> targetType) Return the property value associated with the given key, converted to the given targetType (nevernull
).Return the set of reserved default profile names.Return the value ofSystem.getenv()
.Return the value ofSystem.getProperties()
.protected boolean
isProfileActive
(String profile) Return whether the given profile is active, or if active profiles are empty whether the profile should be active by default.void
merge
(ConfigurableEnvironment parent) Append the given parent environment's active profiles, default profiles and property sources to this (child) environment's respective collections of each.resolvePlaceholders
(String text) Resolve ${...} placeholders in the given text, replacing them with corresponding property values as resolved byPropertyResolver.getProperty(java.lang.String)
.Resolve ${...} placeholders in the given text, replacing them with corresponding property values as resolved byPropertyResolver.getProperty(java.lang.String)
.void
setActiveProfiles
(String... profiles) Specify the set of profiles active for thisEnvironment
.void
setConversionService
(ConfigurableConversionService conversionService) Set theConfigurableConversionService
to be used when performing type conversions on properties.void
setDefaultProfiles
(String... profiles) Specify the set of profiles to be made active by default if no other profiles are explicitly made active throughsetActiveProfiles(java.lang.String...)
.void
setIgnoreUnresolvableNestedPlaceholders
(boolean ignoreUnresolvableNestedPlaceholders) Set whether to throw an exception when encountering an unresolvable placeholder nested within the value of a given property.void
setPlaceholderPrefix
(String placeholderPrefix) Set the prefix that placeholders replaced by this resolver must begin with.void
setPlaceholderSuffix
(String placeholderSuffix) Set the suffix that placeholders replaced by this resolver must end with.void
setRequiredProperties
(String... requiredProperties) Specify which properties must be present, to be verified byConfigurablePropertyResolver.validateRequiredProperties()
.void
setValueSeparator
(String valueSeparator) Specify the separating character between the placeholders replaced by this resolver and their associated default value, ornull
if no such special character should be processed as a value separator.protected boolean
Determine whether to suppressSystem.getenv()
/System.getenv(String)
access for the purposes ofgetSystemEnvironment()
.toString()
protected void
validateProfile
(String profile) Validate the given profile, called internally prior to adding to the set of active or default profiles.void
Validate that each of the properties specified byConfigurablePropertyResolver.setRequiredProperties(java.lang.String...)
is present and resolves to a non-null
value.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.springframework.core.env.Environment
matchesProfiles
-
Field Details
-
IGNORE_GETENV_PROPERTY_NAME
System property that instructs Spring to ignore system environment variables, i.e. to never attempt to retrieve such a variable viaSystem.getenv()
.The default is "false", falling back to system environment variable checks if a Spring environment property (e.g. a placeholder in a configuration String) isn't resolvable otherwise. Consider switching this flag to "true" if you experience log warnings from
getenv
calls coming from Spring.- See Also:
-
ACTIVE_PROFILES_PROPERTY_NAME
Name of the property to set to specify active profiles: "spring.profiles.active".The value may be comma delimited.
Note that certain shell environments such as Bash disallow the use of the period character in variable names. Assuming that Spring's
SystemEnvironmentPropertySource
is in use, this property may be specified as an environment variable namedSPRING_PROFILES_ACTIVE
. -
DEFAULT_PROFILES_PROPERTY_NAME
Name of the property to set to specify profiles that are active by default: "spring.profiles.default".The value may be comma delimited.
Note that certain shell environments such as Bash disallow the use of the period character in variable names. Assuming that Spring's
SystemEnvironmentPropertySource
is in use, this property may be specified as an environment variable namedSPRING_PROFILES_DEFAULT
. -
RESERVED_DEFAULT_PROFILE_NAME
Name of the reserved default profile name: "default".If no default profile names are explicitly set and no active profile names are explicitly set, this profile will automatically be activated by default.
-
logger
-
-
Constructor Details
-
AbstractEnvironment
public AbstractEnvironment()Create a newEnvironment
instance, calling back tocustomizePropertySources(MutablePropertySources)
during construction to allow subclasses to contribute or manipulatePropertySource
instances as appropriate. -
AbstractEnvironment
Create a newEnvironment
instance with a specificMutablePropertySources
instance, calling back tocustomizePropertySources(MutablePropertySources)
during construction to allow subclasses to contribute or manipulatePropertySource
instances as appropriate.- Parameters:
propertySources
- property sources to use- Since:
- 5.3.4
- See Also:
-
-
Method Details
-
createPropertyResolver
protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) Factory method used to create theConfigurablePropertyResolver
instance used by the Environment.- Since:
- 5.3.4
- See Also:
-
getPropertyResolver
Return theConfigurablePropertyResolver
being used by theEnvironment
.- Since:
- 5.3.4
- See Also:
-
customizePropertySources
Customize the set ofPropertySource
objects to be searched by thisEnvironment
during calls togetProperty(String)
and related methods.Subclasses that override this method are encouraged to add property sources using
MutablePropertySources.addLast(PropertySource)
such that further subclasses may callsuper.customizePropertySources()
with predictable results. For example:public class Level1Environment extends AbstractEnvironment { @Override protected void customizePropertySources(MutablePropertySources propertySources) { super.customizePropertySources(propertySources); // no-op from base class propertySources.addLast(new PropertySourceA(...)); propertySources.addLast(new PropertySourceB(...)); } } public class Level2Environment extends Level1Environment { @Override protected void customizePropertySources(MutablePropertySources propertySources) { super.customizePropertySources(propertySources); // add all from superclass propertySources.addLast(new PropertySourceC(...)); propertySources.addLast(new PropertySourceD(...)); } }
In this arrangement, properties will be resolved against sources A, B, C, D in that order. That is to say that property source "A" has precedence over property source "D". If the
Level2Environment
subclass wished to give property sources C and D higher precedence than A and B, it could simply callsuper.customizePropertySources
after, rather than before adding its own:public class Level2Environment extends Level1Environment { @Override protected void customizePropertySources(MutablePropertySources propertySources) { propertySources.addLast(new PropertySourceC(...)); propertySources.addLast(new PropertySourceD(...)); super.customizePropertySources(propertySources); // add all from superclass } }
The search order is now C, D, A, B as desired.
Beyond these recommendations, subclasses may use any of the
add*
,remove
, orreplace
methods exposed byMutablePropertySources
in order to create the exact arrangement of property sources desired.The base implementation registers no property sources.
Note that clients of any
ConfigurableEnvironment
may further customize property sources via thegetPropertySources()
accessor, typically within anApplicationContextInitializer
. For example:ConfigurableEnvironment env = new StandardEnvironment(); env.getPropertySources().addLast(new PropertySourceX(...));
A warning about instance variable access
Instance variables declared in subclasses and having default initial values should not be accessed from within this method. Due to Java object creation lifecycle constraints, any initial value will not yet be assigned when this callback is invoked by the
AbstractEnvironment()
constructor, which may lead to aNullPointerException
or other problems. If you need to access default values of instance variables, leave this method as a no-op and perform property source manipulation and instance variable access directly within the subclass constructor. Note that assigning values to instance variables is not problematic; it is only attempting to read default values that must be avoided. -
getReservedDefaultProfiles
Return the set of reserved default profile names. This implementation returns "default". Subclasses may override in order to customize the set of reserved names. -
getActiveProfiles
Description copied from interface:Environment
Return the set of profiles explicitly made active for this environment. Profiles are used for creating logical groupings of bean definitions to be registered conditionally, for example based on deployment environment. Profiles can be activated by setting "spring.profiles.active" as a system property or by callingConfigurableEnvironment.setActiveProfiles(String...)
.If no profiles have explicitly been specified as active, then any default profiles will automatically be activated.
- Specified by:
getActiveProfiles
in interfaceEnvironment
- See Also:
-
doGetActiveProfiles
Return the set of active profiles as explicitly set throughsetActiveProfiles(java.lang.String...)
or if the current set of active profiles is empty, check for the presence ofdoGetActiveProfilesProperty()
and assign its value to the set of active profiles. -
doGetActiveProfilesProperty
Return the property value for the active profiles.- Since:
- 5.3.4
- See Also:
-
setActiveProfiles
Description copied from interface:ConfigurableEnvironment
Specify the set of profiles active for thisEnvironment
. Profiles are evaluated during container bootstrap to determine whether bean definitions should be registered with the container.Any existing active profiles will be replaced with the given arguments; call with zero arguments to clear the current set of active profiles. Use
ConfigurableEnvironment.addActiveProfile(java.lang.String)
to add a profile while preserving the existing set. -
addActiveProfile
Description copied from interface:ConfigurableEnvironment
Add a profile to the current set of active profiles.- Specified by:
addActiveProfile
in interfaceConfigurableEnvironment
- See Also:
-
getDefaultProfiles
Description copied from interface:Environment
Return the set of profiles to be active by default when no active profiles have been set explicitly.- Specified by:
getDefaultProfiles
in interfaceEnvironment
- See Also:
-
doGetDefaultProfiles
Return the set of default profiles explicitly set viasetDefaultProfiles(String...)
or if the current set of default profiles consists only of reserved default profiles, then check for the presence ofdoGetActiveProfilesProperty()
and assign its value (if any) to the set of default profiles. -
doGetDefaultProfilesProperty
Return the property value for the default profiles.- Since:
- 5.3.4
- See Also:
-
setDefaultProfiles
Specify the set of profiles to be made active by default if no other profiles are explicitly made active throughsetActiveProfiles(java.lang.String...)
.Calling this method removes overrides any reserved default profiles that may have been added during construction of the environment.
- Specified by:
setDefaultProfiles
in interfaceConfigurableEnvironment
- See Also:
-
acceptsProfiles
Deprecated.Description copied from interface:Environment
Determine whether one or more of the given profiles is active — or in the case of no explicit active profiles, whether one or more of the given profiles is included in the set of default profiles.If a profile begins with '!' the logic is inverted, meaning this method will return
true
if the given profile is not active. For example,env.acceptsProfiles("p1", "!p2")
will returntrue
if profile 'p1' is active or 'p2' is not active.- Specified by:
acceptsProfiles
in interfaceEnvironment
- See Also:
-
acceptsProfiles
Description copied from interface:Environment
Determine whether the givenProfiles
predicate matches the active profiles — or in the case of no explicit active profiles, whether the givenProfiles
predicate matches the default profiles.If you wish provide profile expressions directly as strings, use
Environment.matchesProfiles(String...)
instead.- Specified by:
acceptsProfiles
in interfaceEnvironment
- See Also:
-
isProfileActive
Return whether the given profile is active, or if active profiles are empty whether the profile should be active by default.- Throws:
IllegalArgumentException
- pervalidateProfile(String)
-
validateProfile
Validate the given profile, called internally prior to adding to the set of active or default profiles.Subclasses may override to impose further restrictions on profile syntax.
- Throws:
IllegalArgumentException
- if the profile is null, empty, whitespace-only or begins with the profile NOT operator (!).- See Also:
-
getPropertySources
Description copied from interface:ConfigurableEnvironment
Return thePropertySources
for thisEnvironment
in mutable form, allowing for manipulation of the set ofPropertySource
objects that should be searched when resolving properties against thisEnvironment
object. The variousMutablePropertySources
methods such asaddFirst
,addLast
,addBefore
andaddAfter
allow for fine-grained control over property source ordering. This is useful, for example, in ensuring that certain user-defined property sources have search precedence over default property sources such as the set of system properties or the set of system environment variables.- Specified by:
getPropertySources
in interfaceConfigurableEnvironment
- See Also:
-
getSystemProperties
Description copied from interface:ConfigurableEnvironment
Return the value ofSystem.getProperties()
.Note that most
Environment
implementations will include this system properties map as a defaultPropertySource
to be searched. Therefore, it is recommended that this method not be used directly unless bypassing other property sources is expressly intended.- Specified by:
getSystemProperties
in interfaceConfigurableEnvironment
-
getSystemEnvironment
Description copied from interface:ConfigurableEnvironment
Return the value ofSystem.getenv()
.Note that most
Environment
implementations will include this system environment map as a defaultPropertySource
to be searched. Therefore, it is recommended that this method not be used directly unless bypassing other property sources is expressly intended.- Specified by:
getSystemEnvironment
in interfaceConfigurableEnvironment
-
suppressGetenvAccess
protected boolean suppressGetenvAccess()Determine whether to suppressSystem.getenv()
/System.getenv(String)
access for the purposes ofgetSystemEnvironment()
.If this method returns
true
, an empty dummy Map will be used instead of the regular system environment Map, never even trying to callgetenv
and therefore avoiding security manager warnings (if any).The default implementation checks for the "spring.getenv.ignore" system property, returning
true
if its value equals "true" in any case. -
merge
Description copied from interface:ConfigurableEnvironment
Append the given parent environment's active profiles, default profiles and property sources to this (child) environment's respective collections of each.For any identically-named
PropertySource
instance existing in both parent and child, the child instance is to be preserved and the parent instance discarded. This has the effect of allowing overriding of property sources by the child as well as avoiding redundant searches through common property source types, e.g. system environment and system properties.Active and default profile names are also filtered for duplicates, to avoid confusion and redundant storage.
The parent environment remains unmodified in any case. Note that any changes to the parent environment occurring after the call to
merge
will not be reflected in the child. Therefore, care should be taken to configure parent property sources and profile information prior to callingmerge
.- Specified by:
merge
in interfaceConfigurableEnvironment
- Parameters:
parent
- the environment to merge with- See Also:
-
getConversionService
Description copied from interface:ConfigurablePropertyResolver
Return theConfigurableConversionService
used when performing type conversions on properties.The configurable nature of the returned conversion service allows for the convenient addition and removal of individual
Converter
instances:ConfigurableConversionService cs = env.getConversionService(); cs.addConverter(new FooConverter());
-
setConversionService
Description copied from interface:ConfigurablePropertyResolver
Set theConfigurableConversionService
to be used when performing type conversions on properties.Note: as an alternative to fully replacing the
ConversionService
, consider adding or removing individualConverter
instances by drilling intoConfigurablePropertyResolver.getConversionService()
and calling methods such as#addConverter
. -
setPlaceholderPrefix
Description copied from interface:ConfigurablePropertyResolver
Set the prefix that placeholders replaced by this resolver must begin with.- Specified by:
setPlaceholderPrefix
in interfaceConfigurablePropertyResolver
-
setPlaceholderSuffix
Description copied from interface:ConfigurablePropertyResolver
Set the suffix that placeholders replaced by this resolver must end with.- Specified by:
setPlaceholderSuffix
in interfaceConfigurablePropertyResolver
-
setValueSeparator
Description copied from interface:ConfigurablePropertyResolver
Specify the separating character between the placeholders replaced by this resolver and their associated default value, ornull
if no such special character should be processed as a value separator.- Specified by:
setValueSeparator
in interfaceConfigurablePropertyResolver
-
setIgnoreUnresolvableNestedPlaceholders
public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) Description copied from interface:ConfigurablePropertyResolver
Set whether to throw an exception when encountering an unresolvable placeholder nested within the value of a given property. Afalse
value indicates strict resolution, i.e. that an exception will be thrown. Atrue
value indicates that unresolvable nested placeholders should be passed through in their unresolved ${...} form.Implementations of
PropertyResolver.getProperty(String)
and its variants must inspect the value set here to determine correct behavior when property values contain unresolvable placeholders.- Specified by:
setIgnoreUnresolvableNestedPlaceholders
in interfaceConfigurablePropertyResolver
-
setRequiredProperties
Description copied from interface:ConfigurablePropertyResolver
Specify which properties must be present, to be verified byConfigurablePropertyResolver.validateRequiredProperties()
.- Specified by:
setRequiredProperties
in interfaceConfigurablePropertyResolver
-
validateRequiredProperties
Description copied from interface:ConfigurablePropertyResolver
Validate that each of the properties specified byConfigurablePropertyResolver.setRequiredProperties(java.lang.String...)
is present and resolves to a non-null
value.- Specified by:
validateRequiredProperties
in interfaceConfigurablePropertyResolver
- Throws:
MissingRequiredPropertiesException
- if any of the required properties are not resolvable.
-
containsProperty
Description copied from interface:PropertyResolver
Return whether the given property key is available for resolution, i.e. if the value for the given key is notnull
.- Specified by:
containsProperty
in interfacePropertyResolver
-
getProperty
Description copied from interface:PropertyResolver
Return the property value associated with the given key, ornull
if the key cannot be resolved.- Specified by:
getProperty
in interfacePropertyResolver
- Parameters:
key
- the property name to resolve- See Also:
-
getProperty
Description copied from interface:PropertyResolver
Return the property value associated with the given key, ordefaultValue
if the key cannot be resolved.- Specified by:
getProperty
in interfacePropertyResolver
- Parameters:
key
- the property name to resolvedefaultValue
- the default value to return if no value is found- See Also:
-
getProperty
Description copied from interface:PropertyResolver
Return the property value associated with the given key, ornull
if the key cannot be resolved.- Specified by:
getProperty
in interfacePropertyResolver
- Parameters:
key
- the property name to resolvetargetType
- the expected type of the property value- See Also:
-
getProperty
Description copied from interface:PropertyResolver
Return the property value associated with the given key, ordefaultValue
if the key cannot be resolved.- Specified by:
getProperty
in interfacePropertyResolver
- Parameters:
key
- the property name to resolvetargetType
- the expected type of the property valuedefaultValue
- the default value to return if no value is found- See Also:
-
getRequiredProperty
Description copied from interface:PropertyResolver
Return the property value associated with the given key (nevernull
).- Specified by:
getRequiredProperty
in interfacePropertyResolver
- Throws:
IllegalStateException
- if the key cannot be resolved- See Also:
-
getRequiredProperty
Description copied from interface:PropertyResolver
Return the property value associated with the given key, converted to the given targetType (nevernull
).- Specified by:
getRequiredProperty
in interfacePropertyResolver
- Throws:
IllegalStateException
- if the given key cannot be resolved
-
resolvePlaceholders
Description copied from interface:PropertyResolver
Resolve ${...} placeholders in the given text, replacing them with corresponding property values as resolved byPropertyResolver.getProperty(java.lang.String)
. Unresolvable placeholders with no default value are ignored and passed through unchanged.- Specified by:
resolvePlaceholders
in interfacePropertyResolver
- Parameters:
text
- the String to resolve- Returns:
- the resolved String (never
null
) - See Also:
-
resolveRequiredPlaceholders
Description copied from interface:PropertyResolver
Resolve ${...} placeholders in the given text, replacing them with corresponding property values as resolved byPropertyResolver.getProperty(java.lang.String)
. Unresolvable placeholders with no default value will cause an IllegalArgumentException to be thrown.- Specified by:
resolveRequiredPlaceholders
in interfacePropertyResolver
- Returns:
- the resolved String (never
null
) - Throws:
IllegalArgumentException
- if given text isnull
or if any placeholders are unresolvable
-
toString
-