Wednesday, January 23, 2013

Spring Profiles

Much of my web development over the past few years has been with Grails on the back end, and although Grails is built on Spring, it's still a good idea to keep up on the new Spring features - you never know when they'll come in handy.

I recently found myself creating a pure Spring app and missing a feature that I really like in Grails - environment based configuration. Fortunately, Spring 3.1 introduced the concepts of profiles, which is as simple as using the @Profile annotation.

First, configure an application context using the @Configuration annotation.

@Configuration
public class ProductionApplicationContext {
    public SomeBeanInterface myBean() {
        return new MyProductionImplementationOfSomeBean();
    }
}
@Configuration
public class TestApplicationContext {
    public SomeBeanInterface myBean() {
        return new MyTestImplementationOfSomeBean();
    }
}
Now we can specify which profile the context is associated with by adding the @Profile annotation
@Configuration
@Profile("production")
public class ProductionApplicationContext {
 // bean defs 
}
@Configuration
@Profile("development")
public class TestApplicationContext {
  // bean defs
}
Now when you start your app, provide the spring.profiles.active system property to specify the profile(s) to use. You can also specify the default profile to use in your web.xml file by adding the following block
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>production</param-value>
</context-param>