The number of environments that your app has to work on before it goes lives usually depends upon a few of things, including your organizations business processes, the scale of the your app and it’s 'importance' (i.e. if you’re writing the tax collection system for your country’s revenue service then the testing process may be more rigorous than if you’re writing an eCommerce app for a local shop). Just so that you get the picture, below is a quick (and probably incomplete) list of all the different environments that came to mind:
- Local Developer Machine
- Development Test Machine
- The Test Teams Functional Test Machine
- The Integration Test Machine
- Clone Environment (A copy of live)
- Live
- It’s non-standard. Each organization usually has its own way of tackling this problem, with no two methods being quite the same/
- It’s difficult to implement leaving lots of room for errors.
- A different WAR/EAR file has to be created for and deployed on each environment taking time and effort, which could be better spent writing code.
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>db.properties</value> </list> </property> </bean>
Secondly, there are environment specific bean classes such as data sources, which usually differ depending upon how you’re connecting to a database.
For example in development you may have:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${database.driver}</value> </property> <property name="url"> <value>${database.uri}</value> </property> <property name="username"> <value>${database.user}</value> </property> <property name="password"> <value>${database.password}</value> </property> </bean>
...whilst in test or live you'll simply write:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/LiveDataSource"/>
The Spring guidelines say that Spring profiles should only be used the second example above: bean specific classes and that you should continue to use PropertyPlaceholderConfigurer to initialize simple bean properties; however, you may want to use Spring profiles to inject an environment specific PropertyPlaceholderConfigurer in to your Spring context.
Having said that, I’m going to break this convention in my sample code as I want the simplest code possible to demonstrate Spring profile’s features.
Spring Profiles and XML Configuration
In terms of XML configuration, Spring 3.1 introduces the new profile attribute to the beans element of the spring-beans schema:
<beans profile="dev">
It’s this profile attribute that acts as a switch when enabling and disabling profiles in different environments.
To explain all this further I’m going to use the simple idea that your application needs to load a person class, and that person class contains different properties depending upon the environment on which your program is running.
The Person class is very trivial and looks something like this:
public class Person {
private final String firstName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
}
...and is defined in the following XML configuration files:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" profile="test1"> <bean id="employee" class="profiles.Person"> <constructor-arg value="John" /> <constructor-arg value="Smith" /> <constructor-arg value="89" /> </bean> </beans>
...and
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" profile="test2"> <bean id="employee" class="profiles.Person"> <constructor-arg value="Fred" /> <constructor-arg value="ButterWorth" /> <constructor-arg value="23" /> </bean> </beans>
...called test-1-profile.xml and test-2-profile.xml respectively (remember these names, they're important later on). As you can see, the only differences in configuration are the first name, last name and age properties.
Unfortunately, it’s not enough simply to define your profiles, you have to tell Spring which profile you’re loading. This means that following old ‘standard’ code will now fail:
@Test(expected = NoSuchBeanDefinitionException.class)
public void testProfileNotActive() {
// Ensure that properties from other tests aren't set
System.setProperty("spring.profiles.active", "");
ApplicationContext ctx = new ClassPathXmlApplicationContext("test-1-profile.xml");
Person person = ctx.getBean(Person.class);
String firstName = person.getFirstName();
System.out.println(firstName);
}
Fortunately there are several ways of selecting your profile and to my mind the most useful is by using the "spring.profiles.active" system property. For example, the following test will now pass:
System.setProperty("spring.profiles.active", "test1");
ApplicationContext ctx = new ClassPathXmlApplicationContext("test-1-profile.xml");
Person person = ctx.getBean(Person.class);
String firstName = person.getFirstName();
assertEquals("John", firstName);
Obviously, you wouldn’t want to hard code things as I’ve done above and best practice usually means keeping the system properties definitions separate to your application. This gives you the option of using either a simple command line argument such as:
-Dspring.profiles.active="test1"
...or by adding
# Setting a property value spring.profiles.active=test1
to Tomcat’s catalina.properties
So, that’s all there is to it: you create your Spring XML profiles using the beans element profile attribute and switch on the profile you want to use by setting the spring.profiles.active system property to your profile’s name.
Accessing Some Extra Flexibility
However, that’s not the end of the story as the Guy’s at Spring has added a number of ways of programmatically loading and enabling profiles - should you choose to do so.
@Test
public void testProfileActive() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"test-1-profile.xml");
ConfigurableEnvironment env = ctx.getEnvironment();
env.setActiveProfiles("test1");
ctx.refresh();
Person person = ctx.getBean("employee", Person.class);
String firstName = person.getFirstName();
assertEquals("John", firstName);
}
In the code above, I’ve used the new ConfigurableEnvironment class to activate the “test1” profile.
@Test
public void testProfileActiveUsingGenericXmlApplicationContextMultipleFilesSelectTest1() {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ConfigurableEnvironment env = ctx.getEnvironment();
env.setActiveProfiles("test1");
ctx.load("*-profile.xml");
ctx.refresh();
Person person = ctx.getBean("employee", Person.class);
String firstName = person.getFirstName();
assertEquals("John", firstName);
}
However, The Guys At Spring now recommend that you use the GenericApplicationContext class instead of ClassPathXmlApplicationContext and FileSystemXmlApplicationContext as this provides additional flexibility. For example, in the code above, I’ve used GenericApplicationContext’s load(...) method to load a number of configuration files using a wild card:
ctx.load("*-profile.xml");
Remember the filenames from earlier on? This will load both test-1-profile.xml and test-2-profile.xml.
Profiles also include additional flexibility that allows you to activate more than one at a time. If you take a look at the code below, you can see that I’m activating both of my test1 and test2 profiles:
@Test
public void testMultipleProfilesActive() {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ConfigurableEnvironment env = ctx.getEnvironment();
env.setActiveProfiles("test1", "test2");
ctx.load("*-profile.xml");
ctx.refresh();
Person person = ctx.getBean("employee", Person.class);
String firstName = person.getFirstName();
assertEquals("Fred", firstName);
}
Beware, in the case of this example I have two beans with the same id of “employee”, and there’s no way of telling which one is valid and is supposed to take precedence. From my test, I guessing that the second one that’s read overwrites, or masks access to, the first. This is okay as you’re not supposed to have multiple beans with the same name - it’s just something to watch out for when activating multiple profiles.
Finally, one of the better simplifications you can make is to use nested <beans/> elements.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <beans profile="test1"> <bean id="employee1" class="profiles.Person"> <constructor-arg value="John" /> <constructor-arg value="Smith" /> <constructor-arg value="89" /> </bean> </beans> <beans profile="test2"> <bean id="employee2" class="profiles.Person"> <constructor-arg value="Bert" /> <constructor-arg value="William" /> <constructor-arg value="32" /> </bean> </beans> </beans>
This takes away all the tedious mucking about with wild cards and loading multiple files, albeit at the expense of a minimal amount of flexibility.
My next blog concludes my look at Spring profiles, by taking a look at the @Configuration annotation used in conjunction with the new @Profile annotation... so, more on that later.
No comments:
Post a comment