配置Spring Boot通过@ConditionalOnProperty来控制Configuration是否生效

配置Spring Boot通过@ConditionalOnProperty来控制Configuration是否生效

qny: AccessKey: 123 SecretKey: 123 bucket: aaa enable:true

一般动态配置我们会用@value注解或者实现InitializingBean,这里我用的是七牛云的举例,为了解耦合动态的去管理配置文件生效

@Data 
@ConfigurationProperties(prefix=”qny”)
 public class QnyProperties { 
 private String AccessKey; 
 private String SecretKey;
 private String bucket; 
  } 
 

我这里用@ConfigurationProperties(prefix=”qny”) 读取配置文件以前缀为qny去注入,但是还没有交由spring 进行管理配置没有生效
在这里用@EnableConfigurationProperties交由Spring容器通过配置文件去创建QnyProperties

@RequiredArgsConstructor
@EnableConfigurationProperties({QnyProperties.class})
@org.springframework.context.annotation.Configuration
public class QnyAutoConfiguration {
    public final QnyProperties qnyProperties;

    @Bean
    @ConditionalOnMissingBean(QnyProperties.class)
    @ConditionalOnProperty(name = "qny.enable", havingValue = "true", matchIfMissing = true)
    public Configuration configuration(){
        return new Configuration(Region.region0());
    }

    @Bean
    @ConditionalOnProperty(name = "qny.enable", havingValue = "true", matchIfMissing = true)
    public UploadManager uploadManager(Configuration configuration){
        return new UploadManager(configuration);
    }

    @Bean
    @ConditionalOnMissingBean(QnyProperties.class)
    @ConditionalOnProperty(name = "qny.enable", havingValue = "true")
    public String upToken(){
        Auth auth = Auth.create(qnyProperties.getAccessKey(), qnyProperties.getSecretKey());
        return auth.uploadToken(qnyProperties.getBucket());
    }



}

这里的核心注解是Spring boot中有个注解@ConditionalOnProperty,这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值