一、Spring Boot通過(guò)@ConditionalOnProperty來(lái)控制Configuration是否生效
二碘橘、內(nèi)部屬性介紹
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
//數(shù)組小腊,獲取對(duì)應(yīng)property名稱的值,與name不可同時(shí)使用
String[] value() default {};
//property名稱的前綴材泄,可有可無(wú)
String prefix() default "";
//數(shù)組虹统,property完整名稱或部分名稱(可與prefix組合使用弓坞,組成完整的property名稱),與value不可同時(shí)使用
String[] name() default {};
//可與name組合使用车荔,比較獲取到的屬性值與havingValue給定的值是否相同渡冻,相同才加載配置
String havingValue() default "";
//缺少該property時(shí)是否可以加載。如果為true忧便,沒(méi)有該property也會(huì)正常加載族吻;反之報(bào)錯(cuò)
boolean matchIfMissing() default false;
}
}
3帽借、使用方法
- 通過(guò)其兩個(gè)屬性name以及havingValue來(lái)實(shí)現(xiàn)的,其中name用來(lái)從application.properties中讀取某個(gè)屬性值超歌。
- 如果該值為空砍艾,則返回false;
- 如果值不為空,則將該值與havingValue指定的值進(jìn)行比較巍举,如果一樣則返回true;否則返回false脆荷。
- 如果返回值為false,則該configuration不生效懊悯;為true則生效蜓谋。
4、code
@Configuration
//在application.yml"mqtt.enabled"炭分,對(duì)應(yīng)的值為true
@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true")
public class MqttInConfig {
private final MqttMsgHandler mqttMsgHandler;
@Autowired
private MqttProperties mqttProperties;
public MqttInConfig(MqttMsgHandler mqttMsgHandler) {
this.mqttMsgHandler = mqttMsgHandler;
}
}
一桃焕、Spring Boot通過(guò)@ConditionalOnProperty來(lái)控制Configuration是否生效
二、內(nèi)部屬性介紹
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
//數(shù)組捧毛,獲取對(duì)應(yīng)property名稱的值观堂,與name不可同時(shí)使用
String[] value() default {};
//property名稱的前綴,可有可無(wú)
String prefix() default "";
//數(shù)組呀忧,property完整名稱或部分名稱(可與prefix組合使用师痕,組成完整的property名稱),與value不可同時(shí)使用
String[] name() default {};
String havingValue() default "";//可與name組合使用荐虐,比較獲取到的屬性值與havingValue給定的值是否相同七兜,相同才加載配置
//缺少該property時(shí)是否可以加載。如果為true福扬,沒(méi)有該property也會(huì)正常加載;反之報(bào)錯(cuò)
boolean matchIfMissing() default false;
//是否可以松散匹配
boolean relaxedNames() default true;
}
}
3惜犀、使用方法
- 通過(guò)其兩個(gè)屬性name以及havingValue來(lái)實(shí)現(xiàn)的铛碑,其中name用來(lái)從application.properties中讀取某個(gè)屬性值。
- 如果該值為空虽界,則返回false;
- 如果值不為空汽烦,則將該值與havingValue指定的值進(jìn)行比較,如果一樣則返回true;否則返回false莉御。
- 如果返回值為false撇吞,則該configuration不生效;為true則生效礁叔。
4牍颈、code
@Configuration
//在application.yml"mqtt.enabled",對(duì)應(yīng)的值為true
@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true")
public class MqttInConfig {
private final MqttMsgHandler mqttMsgHandler;
@Autowired
private MqttProperties mqttProperties;
public MqttInConfig(MqttMsgHandler mqttMsgHandler) {
this.mqttMsgHandler = mqttMsgHandler;
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者