大数跨境
0
0

SpringBoot根据不同激活配置创建不同的Bean对象@Profile

SpringBoot根据不同激活配置创建不同的Bean对象@Profile Spring全家桶实战案例
2021-09-27
0
导读:SpringBoot根据不同激活配置创建不同的Bean对象@Profile

环境:Springboot2.4.10


@Profile注释允许你在一个或多个指定的概要(配置)文件处于活动(激活)状态时指示组件符合注册条件。

1 简单应用

application.yml

server:  port: 8081---spring:  profiles:    active:    - test

application-test.yml

custom:  name: test  index: 1

application-dev.yml

custom:  name: dev  index: 0

属性配置类

@Component@ConfigurationProperties(prefix = "test")public class CustomProperties {    private String name ;    private Integer index ;}

根据在主配置文件中配置的激活文件spring.profiles.active=test, 那么这里注入的就是test文件中的的配置信息。

2 根据Profile注册Bean

配置文件

@Configurationpublic class ProfileConfig {        @Bean    @ConfigurationProperties(prefix = "custom")    @Profile("dev")    public CustomProperties cp() {        return new CustomProperties() ;    }        @Bean    @Profile("test")    public CustomProperties cp() {        CustomProperties cp = new CustomProperties() ;        cp.setName("测试环境") ;        cp.setIndex(10) ;        return cp ;    }    }

上面的配置会根据spring.profiles.active的配置信息分别注册不同的CustomProperties Bean信息。

3 Profile多条件应用

可以为@Profile配置多个属性值,只要有一个就成功注册Bean

@Bean@ConfigurationProperties(prefix = "custom")@Profile({"dev", "jdbc"})public CustomProperties devJdbc() {    return new CustomProperties() ;}

当spring.profiles.active配置的任何一个包含在dev或jdbc时就成功注册Bean

4 应用逻辑运算

! 非运算符

@Bean@ConfigurationProperties(prefix = "custom")@Profile("!dev")public CustomProperties cp() {    return new CustomProperties() ;}

只要spring.profiles.active不包含dev即注册Bean

& 与运算符

@Bean@ConfigurationProperties(prefix = "custom")@Profile("dev & jdbc")public CustomProperties cp() {    return new CustomProperties() ;}

只要spring.profiles.active包含 dev与jdbc 即注册Bean;注意:也就是激活的必须包含dev与jdbc,可以含有其它的。

| 或运算符

@Bean@ConfigurationProperties(prefix = "custom")@Profile("dev | jdbc")public CustomProperties cp() {    return new CustomProperties() ;}

只要spring.profiles.active包含 dev或者jdbc 即注册Bean。

5 默认配置文件

我们可以把默认的配置文件作为一个默认情况的配置(当没有满足条件的配置激活时应用默认配置)

在配置文件中删除spring.profiles.active配置后,会应用默认的配置

@Bean@Profile("default")public CustomProperties defCP() {    CustomProperties cp = new CustomProperties() ;    cp.setName("default") ;    cp.setIndex(1000) ;    return cp ;}

在没有配置spring.profiles.active时上面的配置会生效。如果配置了spring.profiles.active但是没有符合的条件,那么这里默认配置也不会生效。

完毕!!!


【声明】内容源于网络
0
0
Spring全家桶实战案例
Java全栈开发,前端Vue2/3全家桶;Spring, SpringBoot 2/3, Spring Cloud各种实战案例及源码解读
内容 832
粉丝 0
Spring全家桶实战案例 Java全栈开发,前端Vue2/3全家桶;Spring, SpringBoot 2/3, Spring Cloud各种实战案例及源码解读
总阅读285
粉丝0
内容832