DEV Community

eidher
eidher

Posted on • Edited on

1

Profiles in Spring

Using the Profile annotation in a Configuration class, all the beans in that Configuration class belong to that profile.

@Configuration
@Profile("dev")
public class TestInfrastructureConfig {
}
Enter fullscreen mode Exit fullscreen mode

Using the Profile annotation on a Bean method, that bean belongs to that profile.

@Configuration
public class TestInfrastructureConfig {
  @Bean(name="dataSource")
  @Profile("dev")
  public DataSource dataSourceForDev(){
    ...
  }

  @Bean(name="dataSource")
  @Profile("prod") // or @Profile("!dev")
  public DataSource dataSourceForProd(){
    ...
  }

}
Enter fullscreen mode Exit fullscreen mode

Both profiles have the same bean id but only one profile would be activated.

Activating Profiles

  • Command line: When running the application (better approach)
java -Dspring.profiles.active=dev -jar yourApplication.jar 
Enter fullscreen mode Exit fullscreen mode
  • System property: By code (coupled approach)
System.setProperty("spring.profiles.active", "dev");
Enter fullscreen mode Exit fullscreen mode

Image of Bright Data

Cut Costs, Save Time – Get your datasets ready for action faster than ever.

Save on resources with our ready-to-use datasets designed for quick integration and application.

Reduce Costs

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay