Spring Profiles in XML Config Files

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 you implement Spring profiles, I thought that it would be a good idea to explore the problem that they’re solving, which is 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 and 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 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:

  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 specific 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, with no two methods being 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, which could be better spent writing code.

The differences in the Spring beans configurations can normally be divided into two. Firstly, there are environment specific properties such as URLs and database names. These 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, 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.

Reference: Using Spring Profiles in XML Config from our JCG partner Roger Hughes at the Captain Debug’s Blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


8 − = five



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close