Spring Boot中@ConditionalOnProperty使用詳解


一、概念

Spring Boot通過@ConditionalOnProperty來控制Configuration是否生效

二、源碼分析,@ConditionalOnProperty注解類源碼如下:

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    // 數組,獲取對應property名稱的值,與name不可同時使用
    String[] value() default {};

    // 配置屬性名稱的前綴,比如spring.http.encoding
    String prefix() default "";

    // 數組,配置屬性完整名稱或部分名稱
    // 可與prefix組合使用,組成完整的配置屬性名稱,與value不可同時使用
    String[] name() default {};

    // 可與name組合使用,比較獲取到的屬性值與havingValue給定的值是否相同,相同才加載配置
    String havingValue() default "";

    // 缺少該配置屬性時是否可以加載。如果為true,沒有該配置屬性時也會正常加載;反之則不會生效
    boolean matchIfMissing() default false;
 // 是否可以松散匹配,至今不知道怎么使用的
 boolean relaxedNames() default true;
}

三、使用說明

通過其兩個屬性 name以及 havingValue來實現的,其中 name用來從 application.properties中讀取某個屬性值。
如果該值為空,則返回false;
如果值不為空,則將該值與havingValue指定的值進行比較,如果一樣則返回true;否則返回false。
如果返回值為false,則該configuration不生效;為true則生效。
 
四、案列
@Configuration
//在application.properties配置"mf.assert",對應的值為true
@ConditionalOnProperty(prefix="mf",name = "assert", havingValue = "true")
public class AssertConfig {
    @Autowired
    private HelloServiceProperties helloServiceProperties;
    @Bean
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}

參考文章:

http://www.choupangxia.com/2019/12/09/spring-boot-conditionalonproperty/

https://www.jianshu.com/p/68a75c093023


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM