您好,登錄后才能下訂單哦!
Spring中@Conditional注解的原理是什么,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
@Conditional是Spring4新提供的注解,它的作用是根據(jù)某個(gè)條件加載特定的bean。
我們需要?jiǎng)?chuàng)建實(shí)現(xiàn)類(lèi)來(lái)實(shí)現(xiàn)Condition接口,這是Condition的源碼
public interface Condition { boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2); }
所以我們需要重寫(xiě)matches方法,該方法返回boolean類(lèi)型。
首先我們準(zhǔn)備根據(jù)不同的操作系統(tǒng)環(huán)境進(jìn)行對(duì)容器加載不同的bean,先創(chuàng)建Person
public class Person { }
創(chuàng)建實(shí)現(xiàn)類(lèi)LinuxCondition和WindowCondiction,
LinuxCondition:
public class WindowCondiction implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return true; } }
WindowCondiction:
public class LinuxCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return true; } }
配置類(lèi):給相應(yīng)的bean加上 @Conditional注解,里面的括號(hào)將返回boolean類(lèi)型,返回true則加載bean
@Configuration public class MainConfig { @Profile("window") @Conditional(WindowCondiction.class) @Bean public Person person01(){ return new Person("李思",30); } @Profile("linux") @Conditional(LinuxCondition.class) @Bean public Person person02(){ return new Person("wangwu",35); } }
測(cè)試:現(xiàn)在是按照l(shuí)inux環(huán)境,@Profile注解先匹配linux的bean,再根據(jù)@Conditional 返回的類(lèi)型判斷是否加載bean,這里都設(shè)置返回true,所以應(yīng)該打印
Person{name='wangwu', age=35}
public class CondictionTest { @Test public void test(){ //創(chuàng)建容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); //設(shè)置需要激活的環(huán)境 applicationContext.getEnvironment().setActiveProfiles("linux"); //設(shè)置主配置類(lèi) applicationContext.register(MainProfileConfig.class); //啟動(dòng)刷新容器 applicationContext.refresh(); String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class); for (String name : beanNamesForType){ System.out.println(name); } applicationContext.close(); } }
如果把LinuxCondition的返回值該為false,會(huì)報(bào)找不到bean的異常
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springbean.Person' available
關(guān)于Spring中@Conditional注解的原理是什么問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。