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.  

Reference: Spring, Enterprise Java from our JCG partner Roger Hughes at the Captain Debug’s Blog blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


9 × = twenty seven



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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