DEV Community

eidher
eidher

Posted on • Edited on

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

Top comments (0)