Using Spring 3.1 Profiles

Profiles in Spring 3.1+ give you the ability to define conditional bean configurations based on a profile name, where one of your defined profiles is selected at runtime based on a selected profile name.

For example, if you have certain beans that are needed for running in a certain deployment environment but not needed for others (dev, test or prod), or if certain beans need to be configured differently between different environments, Profiles give you the ability to do exactly this.

If you’re using XML configuration, you use the profile=”…” attribute on the
<beans> element. For example:

    <beans profile="dev">
        ... bean defs for dev profile here

    <beans profile="prod">
        ... bean defs for prod profile here

To select your profile at runtime you’ve got a couple of different options – the easiest approach is to declare a system property, or -D parameter to your JVM at startup:

When you initialize your Application Context, Spring automatically checks for this property and then will initialize only the beans declared for that specific profile. Beans not within a profile will still get initialized, or alternatively a profile with the name ‘default’ will get initialized if no other profile is specified.

Another approach if you need more control over the logic to determine which profile is active on startup, you can programmatically select your profile like this:

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();

if( ... some logic here)


Notice with this approach, since we’re not using the property, we don’t want to load the context xml file until after we’re determined programmatically which profile is active (based on some logic), then we set the profile with setActiveProfiles(), then load the xml, and refresh the context to initialize our beans for the selected profile.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.