Environment and PropertySource Abstraction
From the previous section, you already saw the usage of Spring's profile feature. To set the active profile,
we need to access the Environment interface. The Environment interface is a new abstraction layer
introduced in Spring 3.1; it serves to encapsulate the environment of the running Spring application.
Besides the profile, other key pieces of information encapsulated by the Environment interface are
properties. Properties are used to store the application's underlying environment configuration, such as
the location of the application folder, database connection information, and so on.
The Environment and PropertySource abstraction features in Spring 3.1 assist us as developers in
accessing various configuration information from the running platform. Under the abstraction, all
system properties, environment variables, and application properties are served by the Environment
interface, which Spring populates when bootstrapping the ApplicationContext. Listing 5-59 shows a
simple example.
Listing 5-59. Spring Environment Abstraction Example
package com.apress.prospring3.ch5.env;
import java.util.HashMap;
import java.util.Map;
import
org.springframework.context.support.GenericXmlApplicationContext;
import
org.springframework.core.env.ConfigurableEnvironment;
import
org.springframework.core.env.MapPropertySource;
import
org.springframework.core.env.MutablePropertySources;
public class EnvironmentSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.refresh();
ConfigurableEnvironment env = ctx.getEnvironment();
MutablePropertySources propertySources = env.getPropertySources();
Map appMap = new HashMap();
appMap.put("application.home", "/etc/prospring3/home");
propertySources.addLast(new MapPropertySource("PROSPRING3_MAP", appMap));
System.out.println("user.home: " + System.getProperty("user.home"));
System.out.println("JAVA_HOME: " + System.getenv("JAVA_HOME"));
System.out.println("user.home: " + env.getProperty("user.home"));
System.out.println("JAVA_HOME: " + env.getProperty("JAVA_HOME"));
System.out.println("application.home: " + env.getProperty("application.home"));
}
}
From Listing 5-59, after the ApplicationContext initialization, we get a reference to the
ConfigurableEnvironment interface. Via the interface, a handle to the MutablePropertySources (a default
implementation of the PropertySources interface, which allows manipulation of the contained property
sources) was obtained. Afterward, we construct a map, put the application properties into the map, and
then construct a MapPropertySource class (a PropertySource subclass that reads keys and values from a
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home