Profiles in Spring

Spring Framework (24 Part Series)

1 Spring Configuration
2 External Properties in Spring
20 more parts…
3 Profiles in Spring
4 Spring Expression Language (SpEL)
5 How Spring implements Singleton Beans
6 Converting explicit into implicit configuration in Spring
7 Autowiring in Spring
8 Lazy Beans in Spring
9 @PostConstruct and @PreDestroy in Spring
10 Stereotype and Meta Annotations in Spring
11 Spring’s FactoryBean Interface
12 The Spring Bean Lifecycle
13 Spring AOP
14 Caching in Spring
15 Spring JDBC
16 Spring Transaction Management
17 JPA with Spring
18 JPA with Spring Boot
19 Spring Web MVC
20 Spring Boot for war
21 Spring MVC REST
22 Reactive Spring Applications
23 Spring Security
24 Spring Injection Types

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

Spring Framework (24 Part Series)

1 Spring Configuration
2 External Properties in Spring
20 more parts…
3 Profiles in Spring
4 Spring Expression Language (SpEL)
5 How Spring implements Singleton Beans
6 Converting explicit into implicit configuration in Spring
7 Autowiring in Spring
8 Lazy Beans in Spring
9 @PostConstruct and @PreDestroy in Spring
10 Stereotype and Meta Annotations in Spring
11 Spring’s FactoryBean Interface
12 The Spring Bean Lifecycle
13 Spring AOP
14 Caching in Spring
15 Spring JDBC
16 Spring Transaction Management
17 JPA with Spring
18 JPA with Spring Boot
19 Spring Web MVC
20 Spring Boot for war
21 Spring MVC REST
22 Reactive Spring Applications
23 Spring Security
24 Spring Injection Types

原文链接:Profiles in Spring

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容