Using Spring 3.1 Profile to run a web application in different environment

Spring 3.1 introduces a neat bean definition profiles features. Basically, you can define beans with different profiles and then set the active profiles to use at runtime for the application. A typical example would be to have different data source beans for development and production environments. This article will provide a quick how-to on configuring Spring to run a web application in different environments using Spring profiles.

1. Bean Definitions

The Spring 3.1 beans XML schema allow nested <beans/> elements and you can include a profile attribute to define one or more profiles to use for the beans.

<beans …>

<beans profiles=”dev”>

// define beans for dev environment

<bean …>


<beans profiles=”prod”>

// define beans for prod environment

<bean …>


Note that:

(1) Multiple profiles can be defined by separating profiles with spaces, commas or semi-colons.

(2) The beans defined in the element are ignored if none of the profiles are activated.

(3) Beans without a profile will always be included.

2. Activate Profiles to use

There are 2 ways to activate the profiles to use:

(1) By defining the -D system properties “”. For example,

java …

(2) By setting the active profiles at runtime programmatically via application context initializer. Register the context intializer class in web.xml file:


and implement class, for example:

public class ContextProfileInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {

public void initialize(ConfigurableWebApplicationContext ctx) {

ConfigurableEnvironment environment = ctx.getEnvironment();

// logic to decide active profiles

String profiles = getProfiles();



Obviously, method (2) is more flexible but involves more work.

Setting profile in integration tests

Spring 3.1 M2 introduces the @ActiveProfile tag which comes in handle when writing integration test. For example:

@ContextConfiguration(locations = “classpath:/spring/app-config.xml”)

public class MyIntegrationTest {


Spring Blog: Spring Framework 3.1 M1: Introducing @Profile

Spring 3.1 schema xsd

About these ads

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

One Response to Using Spring 3.1 Profile to run a web application in different environment

  1. John Kroubalkian says:

    Thank you Raymond. Exactly what I was looking for.