Enterprise Integration Zone is brought to you in partnership with:

Lives in the UK. Likes blogging, cycling and eating lemon drizzle cake. Roger is a DZone MVB and is not an employee of DZone and has posted 143 posts at DZone. You can read more from them at their website. View Full User Profile

Using Spring Profiles in XML Config

08.14.2012
| 34664 views |
  • submit to reddit
My last blog was very simple as it covered my painless upgrade from Spring 3.0.x to Spring 3.1.x and I finished by mentioning that you can upgrade your Spring schemas to 3.1 to allow you to take advantage of Spring’s newest features. In today’s blog, I'm going to cover one of the coolest of these features: Spring profiles. But, before talking about how to implement Spring profiles, I thought it would be a good idea to explore the problem that they’re solving, which you'll need to create different Spring configurations for different environments. This usually arises because your app needs to connect to several similar external resources during its development lifecycle, and, more often than not, these ‘external resources’ are usually databases, although they could be JMS queues, web services, remote EJBs, etc.

The number of environments that your app has to work on before it goes lives usually depends upon a few of things, including your organization's business processes, the scale of the your app and its '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:
  1. Local Developer Machine
  2. Development Test Machine
  3. The Test Teams Functional Test Machine
  4. The Integration Test Machine
  5. Clone Environment (A copy of live)
  6. Live
This is not a new problem and it’s usually solved by creating a set of Spring XML and properties files for each environment. The XML files usually consist of a master file that imports other environment-files. These are then coupled together at compile time to create different WAR or EAR files. This method has worked for years, but it does have a few problems:
  1. It’s non-standard. Each organization usually has its own way of tackling this problem; no two methods are quite the same.
  2. It’s difficult to implement leaving lots of room for errors.
  3. A different WAR/EAR file has to be created for and deployed on each environment, taking time and effort that could be better spent writing code.
The differences in the Spring beans configurations can normally be divided into two. Firstly, environment-specific properties, such as URLs and database names, are usually injected into Spring XML files using the PropertyPlaceholderConfigurer class and the associated ${} notation.

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>db.properties</value>
            </list>
        </property>
    </bean>

Secondly, environment-specific bean classes, such as data sources, 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 use the second example above — bean-specific classes. And 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 into 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 it 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>

This, too, is included:
 
<?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>

These are called the 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 simply not enough 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, we know several ways of selecting your profile. In my opinion, 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 the 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, additionally:  
# 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 have added a number of ways to programmatically load and enable profiles. Should you choose to do so, here's some code for that:

  @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 you use the GenericApplicationContext class instead of ClassPathXmlApplicationContext and FileSystemXmlApplicationContext. Doing that provides additional flexibility. For example, in the code above, I’ve used GenericApplicationContext’s load(...) method to load a number of configuration files by using the following wild card:
    ctx.load("*-profile.xml");

Remember the filenames from earlier? 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 guess the second one that is read overwrites, or masks access to, the first. This is okay as you’re not supposed to have multiple beans with the same name, but it’s 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 of multiple files, albeit at the expense of a minimal amount of flexibility.

My next blog concludes my look at Spring profiles. It will explore the @Configuration annotation used in conjunction with the new @Profile annotation. So, more on that later. 
Published at DZone with permission of Roger Hughes, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)