Thursday, 23 August 2012

Using Spring Profiles and Java Configuration

My last blog introduced Spring 3.1’s profiles and explained both the business case for using them and demonstrated their use with Spring XML configuration files. It seems, however, that a good number of developers prefer using Spring’s Java based application configuration and so Spring have designed a way of using profiles with their existing @Configuration annotation.

I’m going to demonstrate profiles and the @Configuration annotation using the Person class from my previous blog. This is a simple bean class whose properties vary depending upon which profile is active.

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;
 
}
}

Remember that the Guys at Spring recommend that Spring profiles should only be used when you need to load different types or sets of classes and that for setting properties you should continue using the PropertyPlaceholderConfigurer. The reason I’m breaking the rules is that I want to try to write the simplest code possible to demonstrate profiles and Java configuration.

At the heart of using Spring profiles with Java configuration is Spring’s new @Profile annotation. The @Profile annotation is used attach a profile name to an @Configuration annotation. It takes a single parameter that can be used in two ways. Firstly to attach a single profile to an @Configuration annotation:

@Profile("test1")

and secondly, to attach multiple profiles:

@Profile({ "test1", "test2" })

Again, I’m going to define two profiles “test1” and “test2” and associate each with a configuration file. Firstly “test1”:

@Configuration
@Profile
("test1")
public class Test1ProfileConfig {

 
@Bean
 
public Person employee() {

   
return new Person("John", "Smith", 55);
 
}
}

...and then “test2”:

@Configuration
@Profile
("test2")
public class Test2ProfileConfig {

 
@Bean
 
public Person employee() {

   
return new Person("Fred", "Williams", 22);
 
}
}

In the code above, you can see that I'm creating a Person bean with an effective id of employee (this is from the method name) that returns differing property values in each profile.

Also note that the @Profile is marked as:

@Target(value=TYPE)

...which means that is can only be placed next to the @Configuration annotation.

Having attached an @Profile to an @Configuration, the next thing to do is to activate your selected @Profile. This uses exactly the same principles and techniques that I described in my last blog and again, to my mind, the most useful activation technique is to use the "spring.profiles.active" system property.

  @Test
 
public void testProfileActiveUsingSystemProperties() {

   
System.setProperty("spring.profiles.active", "test1");
    ApplicationContext ctx =
new ClassPathXmlApplicationContext("profiles-config.xml");

    Person person = ctx.getBean
("employee", 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 configuration separate from 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 profiles by annotating an @Configuration with an @Profile annotation and then switching on the profile you want to use by setting the spring.profiles.active system property to your profile’s name.

As usual, the Guys at Spring don’t just confine you to using system properties to activate profiles, you can do things programatically. For example, the following code creates an AnnotationConfigApplicationContext and then uses an Environment object to activate the “test1” profile, before registering our @Configuration classes.

  @Test
 
public void testAnnotationConfigApplicationContextThatWorks() {

   
// Can register a list of config classes
   
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.getEnvironment
().setActiveProfiles("test1");
    ctx.register
(Test1ProfileConfig.class, Test2ProfileConfig.class);
    ctx.refresh
();

    Person person = ctx.getBean
("employee", Person.class);
    String firstName = person.getFirstName
();
    assertEquals
("John", firstName);
 
}

This is all fine and good, but beware, you need to call AnnotationConfigApplicationContext’s methods in the right order. For example, if you register your @Configuration classes before you specify your profile, then you’ll get an IllegalStateException.

  @Test(expected = IllegalStateException.class)
 
public void testAnnotationConfigApplicationContextThatFails() {

   
// Can register a list of config classes
   
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
       
Test1ProfileConfig.class, Test2ProfileConfig.class);
    ctx.getEnvironment
().setActiveProfiles("test1");
    ctx.refresh
();

    Person person = ctx.getBean
("employee", Person.class);
    String firstName = person.getFirstName
();
    assertEquals
("John", firstName);
 
}

Before closing today’s blog, the code below demonstrates the ability to attach multiple @Profiles to an @Configuration annotation.

@Configuration
@Profile
({ "test1", "test2" })
public class MulitpleProfileConfig {

 
@Bean
 
public Person tourDeFranceWinner() {

   
return new Person("Bradley", "Wiggins", 32);
 
}
}


  @Test
 
public void testMulipleAssignedProfilesUsingSystemProperties() {

   
System.setProperty("spring.profiles.active", "test1");
    ApplicationContext ctx =
new ClassPathXmlApplicationContext("profiles-config.xml");

    Person person = ctx.getBean
("tourDeFranceWinner", Person.class);
    String firstName = person.getFirstName
();
    assertEquals
("Bradley", firstName);

    System.setProperty
("spring.profiles.active", "test2");
    ctx =
new ClassPathXmlApplicationContext("profiles-config.xml");

    person = ctx.getBean
("tourDeFranceWinner", Person.class);
    firstName = person.getFirstName
();
    assertEquals
("Bradley", firstName);
 
}

In the code above, 2012 Tour De France winner Bradley Wiggins appears in both the “test1” and “test2” profiles.

4 comments:

Unknown said...

Hi Roger

Thanks for sharing this article. This is what i am looking for. Actually, I am working on Spring 3 and implementing same thing in my project using spring 3. I am wondering if you have source code that covers different profiles like dev, testing which reads the properties database properties files or log file using spring 3.

I have couple of questions:

1) How can we create session factory in Spring 3 using PropertyPlaceholderConfigurer?

3) For Spring Profiling, is there any way available to set profiles.active="test1" only once in application rather including (profile="test") annotation in every class? i know you have covered few things in this article but i am bit confused.

If you have source code for these things what i have mentioned in this post, then can you please upload here.

Thanks,
Zaghman Arshad

Roger Hughes said...

Not quite sure what you mean in your first question. If you read my blog again you'll see that Spring don't recommend using profiles simply for setting bean properties using PropertyPlaceholderConfigurer , they're really for creating different Spring context configurations (i.e. groups of beans held in an application context) for different environments.


You only need to add the profile=test etc. into you Java configuration classes, that is the ones you annotate with @Configuration. These classes can be used to create the objects that you require as part of your Spring context. The idea here is that you would write a different configuration class for each profile - eg one for test, one for dev, one for production etc. These would then create different versions of your Spring context objects, which are all neatly referenced using interfaces.

Anonymous said...

Thanks Roger for your reply.
I have declared one profile in web.xml like

context-param
param name
spring.profiles.active /param-name
param-value dev /param-value
/context-param

Can you tell me how can i get value of active profile in Java class?

Here is piece of code.
public static void main(String args[]){
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().getActiveProfiles();

But it doesn't work due to some reasons

Roger Hughes said...

You can only declare a profile using web.xml if you're using a web server. In the sample you've given, you're trying to load web.xml from a main() method. If you want to use main() then the first thing to try would be to specify your profile using a -D arg as described above. You'll also need to load your Spring config file.