DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
  • Composing Custom Annotations in Spring
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Enforcing Architecture With ArchUnit in Java
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • How Can Developers Drive Innovation by Combining IoT and AI?
  1. DZone
  2. Coding
  3. Languages
  4. Using Spring Profiles and Java Configuration

Using Spring Profiles and Java Configuration

By 
Roger Hughes user avatar
Roger Hughes
·
Aug. 30, 12 · Interview
Likes (6)
Comment
Save
Tweet
Share
129.1K Views

Join the DZone community and get the full member experience.

Join For Free

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, 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.

Profile (engineering) Spring Framework Java (programming language) Annotation

Published at DZone with permission of Roger Hughes, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
  • Composing Custom Annotations in Spring
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: