Spring @Conditional注解講解及示例詳解
前言:
@Conditional是Spring4新提供的注解,它的作用是按照一定的條件進(jìn)行判斷,滿足條件給容器注冊(cè)bean。
@Conditional的定義:
//此注解可以標(biāo)注在類和方法上 @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Conditional { Class<? extends Condition>[] value(); }
從代碼中可以看到,需要傳入一個(gè)Class數(shù)組,并且需要繼承Condition接口:
public interface Condition { boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2); }
Condition是個(gè)接口,需要實(shí)現(xiàn)matches方法,返回true則注入bean,false則不注入。
示例:
首先,創(chuàng)建Person類:
public class Person { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
創(chuàng)建BeanConfig類,用于配置兩個(gè)Person實(shí)例并注入,一個(gè)是比爾蓋茨,一個(gè)是林納斯。
@Configuration public class BeanConfig { @Bean(name = "bill") public Person person1(){ return new Person("Bill Gates",62); } @Bean("linus") public Person person2(){ return new Person("Linus",48); } }
接著寫(xiě)一個(gè)測(cè)試類進(jìn)行驗(yàn)證這兩個(gè)Bean是否注入成功。
public class ConditionalTest { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class); @Test public void test1(){ Map<String, Person> map = applicationContext.getBeansOfType(Person.class); System.out.println(map); } }
運(yùn)行,輸出結(jié)果是這樣的,兩個(gè)Person實(shí)例被注入進(jìn)容器。
這是一個(gè)簡(jiǎn)單的例子,現(xiàn)在問(wèn)題來(lái)了,如果我想根據(jù)當(dāng)前操作系統(tǒng)來(lái)注入Person實(shí)例,windows下注入bill,linux下注入linus,怎么實(shí)現(xiàn)呢?
這就需要我們用到@Conditional注解了,前言中提到,需要實(shí)現(xiàn)Condition接口,并重寫(xiě)方法來(lái)自定義match規(guī)則。
首先,創(chuàng)建一個(gè)WindowsCondition類:
public class WindowsCondition implements Condition { /** * @param conditionContext:判斷條件能使用的上下文環(huán)境 * @param annotatedTypeMetadata:注解所在位置的注釋信息 * */ @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { //獲取ioc使用的beanFactory ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory(); //獲取類加載器 ClassLoader classLoader = conditionContext.getClassLoader(); //獲取當(dāng)前環(huán)境信息 Environment environment = conditionContext.getEnvironment(); //獲取bean定義的注冊(cè)類 BeanDefinitionRegistry registry = conditionContext.getRegistry(); //獲得當(dāng)前系統(tǒng)名 String property = environment.getProperty("os.name"); //包含Windows則說(shuō)明是windows系統(tǒng),返回true if (property.contains("Windows")){ return true; } return false; } }
matches方法的兩個(gè)參數(shù)的意思在注釋中講述了,值得一提的是,conditionContext提供了多種方法,方便獲取各種信息,也是SpringBoot中 @ConditonalOnXX注解多樣擴(kuò)展的基礎(chǔ)。
接著,創(chuàng)建LinuxCondition類:
public class LinuxCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { Environment environment = conditionContext.getEnvironment(); String property = environment.getProperty("os.name"); if (property.contains("Linux")){ return true; } return false; } }
接著就是使用這兩個(gè)類了,因?yàn)榇俗⒔饪梢詷?biāo)注在方法上和類上,所以分開(kāi)測(cè)試:
標(biāo)注在方法上:
修改BeanConfig:
@Configuration public class BeanConfig { //只有一個(gè)類時(shí),大括號(hào)可以省略 //如果WindowsCondition的實(shí)現(xiàn)方法返回true,則注入這個(gè)bean @Conditional({WindowsCondition.class}) @Bean(name = "bill") public Person person1(){ return new Person("Bill Gates",62); } //如果LinuxCondition的實(shí)現(xiàn)方法返回true,則注入這個(gè)bean @Conditional({LinuxCondition.class}) @Bean("linus") public Person person2(){ return new Person("Linus",48); } }
修改測(cè)試方法,使其可以打印當(dāng)前系統(tǒng)名:
@Test public void test1(){ String osName = applicationContext.getEnvironment().getProperty("os.name"); System.out.println("當(dāng)前系統(tǒng)為:" + osName); Map<String, Person> map = applicationContext.getBeansOfType(Person.class); System.out.println(map); }
運(yùn)行結(jié)果如下:
我是運(yùn)行在windows上的所以只注入了bill,嗯,沒(méi)毛病。
接著實(shí)驗(yàn)linux下的情況,不能運(yùn)行在linux下,但可以修改運(yùn)行時(shí)參數(shù):
修改后啟動(dòng)測(cè)試方法:
一個(gè)方法只能注入一個(gè)bean實(shí)例,所以@Conditional標(biāo)注在方法上只能控制一個(gè)bean實(shí)例是否注入。
標(biāo)注在類上:
一個(gè)類中可以注入很多實(shí)例,@Conditional標(biāo)注在類上就決定了一批bean是否注入。
我們?cè)囈幌?,將BeanConfig改寫(xiě),這時(shí),如果WindowsCondition返回true,則兩個(gè)Person實(shí)例將被注入(注意:上一個(gè)測(cè)試將os.name改為linux,這是我將把這個(gè)參數(shù)去掉):
@Conditional({WindowsCondition.class}) @Configuration public class BeanConfig { @Bean(name = "bill") public Person person1(){ return new Person("Bill Gates",62); } @Bean("linus") public Person person2(){ return new Person("Linus",48); } }
結(jié)果兩個(gè)實(shí)例都被注入:
如果將類上的WindowsCondition.class改為L(zhǎng)inuxCondition.class,結(jié)果應(yīng)該可以猜到:
結(jié)果就是空的,類中所有bean都沒(méi)有注入。
多個(gè)條件類:
前言中說(shuō),@Conditional注解傳入的是一個(gè)Class數(shù)組,存在多種條件類的情況。
這種情況貌似判斷難度加深了,測(cè)試一波,新增新的條件類,實(shí)現(xiàn)的matches返回false(這種寫(xiě)死返回false的方法純屬測(cè)試用,沒(méi)有實(shí)際意義O(∩_∩)O)
public class ObstinateCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return false; } }
BeanConfig修改一下:
@Conditional({WindowsCondition.class,ObstinateCondition.class}) @Configuration public class BeanConfig { @Bean(name = "bill") public Person person1(){ return new Person("Bill Gates",62); } @Bean("linus") public Person person2(){ return new Person("Linus",48); } }
結(jié)果:
現(xiàn)在如果將ObstinateCondition的matches方法返回值改成true,兩個(gè)bean就被注入進(jìn)容器:
結(jié)論得:
第一個(gè)條件類實(shí)現(xiàn)的方法返回true,第二個(gè)返回false,則結(jié)果false,不注入進(jìn)容器。
第一個(gè)條件類實(shí)現(xiàn)的方法返回true,第二個(gè)返回true,則結(jié)果true,注入進(jìn)容器中。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
logback的UNDEFINED_PROPERTY屬性源碼執(zhí)行流程解讀
這篇文章主要為大家介紹了logback的UNDEFINED_PROPERTY屬性源碼執(zhí)行流程解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11詳解如何Java中實(shí)現(xiàn)Excel的注釋和批注
注釋及批注是?Excel?中比較常用的功能,這篇文章主要為大家詳細(xì)介紹了如何在Java中實(shí)現(xiàn)Excel的注釋和批注,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12Spring Boot 2.7.6整合redis與低版本的區(qū)別
這篇文章主要介紹了Spring Boot 2.7.6整合redis與低版本的區(qū)別,文中補(bǔ)充介紹了SpringBoot各個(gè)版本使用Redis之間的區(qū)別實(shí)例講解,需要的朋友可以參考下2023-02-02SpringBoot集成Redis實(shí)現(xiàn)消息隊(duì)列的方法
這篇文章主要介紹了SpringBoot集成Redis實(shí)現(xiàn)消息隊(duì)列的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02Java中的讀寫(xiě)鎖ReentrantReadWriteLock源碼分析
這篇文章主要介紹了Java中的讀寫(xiě)鎖ReentrantReadWriteLock源碼分析,ReentrantReadWriteLock 分為讀鎖和寫(xiě)鎖兩個(gè)實(shí)例,讀鎖是共享鎖,可被多個(gè)線程同時(shí)使用,寫(xiě)鎖是獨(dú)占鎖,持有寫(xiě)鎖的線程可以繼續(xù)獲取讀鎖,反之不行,需要的朋友可以參考下2023-12-12SpringBoot整合Jasypt實(shí)現(xiàn)配置加密的步驟詳解
Jasypt是一個(gè)Java庫(kù),提供了一種簡(jiǎn)單的加密解密方式,可用于保護(hù)敏感數(shù)據(jù),例如密碼、API密鑰和數(shù)據(jù)庫(kù)連接信息等,本文給大家介紹了SpringBoot整合Jasypt實(shí)現(xiàn)配置加密的詳細(xì)步驟,感興趣的同學(xué)可以參考一下2023-11-11JAVA使用JDBC技術(shù)操作SqlServer數(shù)據(jù)庫(kù)實(shí)例代碼
本篇文章主要介紹了JAVA使用JDBC技術(shù)操作SqlServer數(shù)據(jù)庫(kù)實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01