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