如何使用SpringBootCondition更自由地定義條件化配置
Conditional如何使用
@Conditional 是 SpringFramework 的功能, SpringBoot 在它的基礎(chǔ)上定義了 @ConditionalOnClass , @ConditionalOnProperty 的一系列的注解來(lái)實(shí)現(xiàn)更豐富的內(nèi)容。
定義一個(gè)自定義標(biāo)簽
import com.example.conditional.MyConditional; import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(MyConditional.class) public @interface MyConditionalIAnnotation { String key(); String value(); }
自定義Conditional
import com.example.conditional.interfaceI.MyConditionalIAnnotation; import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; public class MyConditional extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(MyConditionalIAnnotation.class.getName()); Object key = annotationAttributes.get("key");// Object value = annotationAttributes.get("value"); if(key == null || value == null){ return new ConditionOutcome(false, "error"); } //獲取environment中的值 String key1 = context.getEnvironment().getProperty(key.toString()); if (value.equals(key1)) { //如果environment中的值與指定的value一致,則返回true return new ConditionOutcome(true, "ok"); } return new ConditionOutcome(false, "error"); } }
config配置
import com.example.conditional.interfaceI.MyConditionalIAnnotation; import com.example.conditional.service.MyConditionalService; import org.apache.log4j.Logger; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration public class MyConditionalConfig { public static Logger logger=Logger.getLogger(MyConditionalService.class); /** * 判斷MyConditional 是否符合條件,是則運(yùn)行MyConditionalService * @return */ @MyConditionalIAnnotation(key = "com.example.conditional", value = "lbl") @ConditionalOnClass(MyConditionalService.class) @Bean public MyConditionalService initMyConditionService() { logger.info("MyConditionalService已加載。"); return new MyConditionalService(); } }
配置文件:application.propeties
spring.application.name=gateway server.port=8084 #conditional 動(dòng)態(tài)配置,判斷該值是否等于lbl,是則創(chuàng)建MyConditionalService實(shí)例 com.example.conditional=lbl #支持自定義aop spring.aop.auto=true
SpringBootCondition 定義條件化配置
1 條件化配置
Spring提供了多種實(shí)現(xiàn)化條件化配置的選擇,如ConditionalOnProperty和ConditionalOnClass等。
用法如下:
@ConditionalOnProperty(prefix = "pkslow", name = "service", havingValue = "larry")
還有:
@ConditionalOnBean(僅僅在當(dāng)前上下文中存在某個(gè)對(duì)象時(shí),才會(huì)實(shí)例化一個(gè)Bean) @ConditionalOnClass(某個(gè)class位于類(lèi)路徑上,才會(huì)實(shí)例化一個(gè)Bean) @ConditionalOnExpression(當(dāng)表達(dá)式為true的時(shí)候,才會(huì)實(shí)例化一個(gè)Bean) @ConditionalOnMissingBean(僅僅在當(dāng)前上下文中不存在某個(gè)對(duì)象時(shí),才會(huì)實(shí)例化一個(gè)Bean) @ConditionalOnMissingClass(某個(gè)class類(lèi)路徑上不存在的時(shí)候,才會(huì)實(shí)例化一個(gè)Bean) @ConditionalOnNotWebApplication(不是web應(yīng)用)
但有時(shí)候我們需要更靈活的自定義條件配置,這時(shí)可以通過(guò)繼承SpringBootCondition類(lèi)來(lái)實(shí)現(xiàn)。
2 繼承SpringBootCondition
自己根據(jù)需求實(shí)現(xiàn)自己的判斷邏輯,我的實(shí)現(xiàn)如下:
public class PkslowCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { BindResult<List<String>> maxBindResult = Binder.get(context.getEnvironment()).bind("pkslow.condition.max", Bindable.listOf(String.class)); BindResult<List<String>> minBindResult = Binder.get(context.getEnvironment()).bind("pkslow.condition.min", Bindable.listOf(String.class)); if ( (maxBindResult.isBound() && !maxBindResult.get().isEmpty()) && (minBindResult.isBound() && !minBindResult.get().isEmpty()) ) { List<String> maxs = maxBindResult.get(); List<String> mins = minBindResult.get(); int max = Integer.parseInt(maxs.get(0)); int min = Integer.parseInt(mins.get(0)); if (max < 1000 && min > 0) { return ConditionOutcome.match(); } } return ConditionOutcome.noMatch("pkslow.condition.max/pkslow.condition.min not matches"); } }
表示需要有配置屬性pkslow.condition.max/pkslow.condition.min才會(huì)生效,并且要求max<1000且min>0。
3 使用
完成自定義的條件類(lèi)后,就可以使用它來(lái)限定一個(gè)配置類(lèi)是否要生效了,使用如下:
@Conditional(PkslowCondition.class) @Configuration public class PkslowConfig { @PostConstruct public void postConstruct() { System.out.println("PkslowConfig called"); } }
4 總結(jié)
代碼請(qǐng)查看:https://github.com/LarryDpk/pkslow-samples
以上就是如何使用SpringBootCondition更自由地定義條件化配置的詳細(xì)內(nèi)容,更多關(guān)于SpringBootCondition 定義條件化配置的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java實(shí)現(xiàn)簡(jiǎn)易貪吃蛇游戲
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)易貪吃蛇游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12Day14基礎(chǔ)不牢地動(dòng)山搖-Java基礎(chǔ)
這篇文章主要給大家介紹了關(guān)于Java中方法使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08Java開(kāi)發(fā)基礎(chǔ)日期類(lèi)代碼詳解
這篇文章主要介紹了Java開(kāi)發(fā)基礎(chǔ)日期類(lèi)的相關(guān)內(nèi)容,代碼通過(guò)日期工具類(lèi)獲取指定月份的星期與日期對(duì)應(yīng)關(guān)系,以及獲取指定月份的所有日期與星期集合等,具有一定參考價(jià)值,需要的朋友可以了解下。2017-10-10MyBatis Properties及別名定義實(shí)例詳解
這篇文章主要介紹了MyBatis Properties及別名定義實(shí)例詳解,需要的朋友可以參考下2017-08-08SpringBoot利用自定義json序列化器實(shí)現(xiàn)敏感字段數(shù)據(jù)脫敏詳解
這篇文章主要介紹了SpringBoot利用自定義json序列化器實(shí)現(xiàn)敏感字段數(shù)據(jù)脫敏詳解,因?yàn)榘咐a用到了hutool提供的DesensitizedUtil數(shù)據(jù)脫敏工具類(lèi),這里要引入hutool的依賴(lài),如果你需要自定義 數(shù)據(jù)脫敏的邏輯,可以不引入這個(gè)依賴(lài),需要的朋友可以參考下2024-01-01基于Java代碼實(shí)現(xiàn)游戲服務(wù)器生成全局唯一ID的方法匯總
我們?cè)谧龇?wù)器系統(tǒng)開(kāi)發(fā)的時(shí)候,為了適應(yīng)數(shù)據(jù)大并發(fā)的請(qǐng)求,需要插入數(shù)據(jù)庫(kù)之前生成一個(gè)全局的唯一id,糾結(jié)全局唯一id怎么生成呢?下面小編給大家分享Java代碼實(shí)現(xiàn)游戲服務(wù)器生成全局唯一ID的方法匯總,涉及到優(yōu)劣勢(shì)方面的知識(shí)點(diǎn),對(duì)此感興趣的朋友一起看看吧2016-10-10