1. 简介

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

2. 说明

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ ElementType.TYPE, ElementType.METHOD })
  3. @Documented
  4. @Conditional(OnPropertyCondition.class)
  5. public @interface ConditionalOnProperty {
  6. String[] value() default {}; //数组,获取对应property名称的值,与name不可同时使用
  7. String prefix() default "";//property名称的前缀,可有可无
  8. String[] name() default {};//数组,property完整名称或部分名称(可与prefix组合使用,组成完整的property名称),与value不可同时使用
  9. String havingValue() default "";//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
  10. boolean matchIfMissing() default false;//缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错
  11. boolean relaxedNames() default true;//是否可以松散匹配。指命名方式 支持驼峰横线方式兼容
  12. }

3. 使用方法

通过其两个属性 name 以及 havingValue 来实现的, 其中 name 用来从 application.properties 中读取某个属性值。

  • 如果该值为空,则返回 false;
  • 如果值不为空,则将该值与 havingValue 指定的值进行比较,如果一样则返回 true;否则返回 false。
  • 如果返回值为 false,则该 configuration 不生效;为 true 则生效。

4. code

  1. @Configuration
  2. //在application.properties配置"mf.assert",对应的值为true
  3. @ConditionalOnProperty(prefix="mf",name = "assert", havingValue = "true")
  4. public class AssertConfig {
  5. @Autowired
  6. private HelloServiceProperties helloServiceProperties;
  7. @Bean
  8. public HelloService helloService(){
  9. HelloService helloService = new HelloService();
  10. helloService.setMsg(helloServiceProperties.getMsg());
  11. return helloService;
  12. }
  13. }

5. 生产实例

  1. @Service
  2. @DependsOn("rateLimiter")
  3. @RequiredArgsConstructor
  4. @ConditionalOnProperty(prefix = LimitConstants.PREFIX, name = "algorithm", havingValue = "counter", matchIfMissing = true)
  5. public class CounterAlgorithmImpl implements RateLimiterAlgorithm {
  6. @NonNull
  7. private RateLimiter rateLimiter;
  8. public void consume(String key, long limit, long lrefreshInterval){
  9. rateLimiter.counterConsume(key,limit,lrefreshInterval);
  10. }
  11. }

6. 收获

springboot注解丰富,我们可以利用好这些注解来实现我们自定义的 starter 配置,减少硬编码的校验,降低组件间的耦合性!!!

作者:wyatt_plus 链接:https://www.jianshu.com/p/68a75c093023 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。