Spring?@Conditional注解示例詳細(xì)講解
前言:
@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); } }
接著寫一個(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)在問題來了,如果我想根據(jù)當(dāng)前操作系統(tǒng)來注入Person實(shí)例,windows下注入bill,linux下注入linus,怎么實(shí)現(xiàn)呢?
這就需要我們用到@Conditional注解了,前言中提到,需要實(shí)現(xiàn)Condition接口,并重寫方法來自定義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則說明是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)注在方法上和類上,所以分開測(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,嗯,沒毛病。
接著實(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改寫,這時(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都沒有注入。
多個(gè)條件類:
前言中說,@Conditional注解傳入的是一個(gè)Class數(shù)組,存在多種條件類的情況。
這種情況貌似判斷難度加深了,測(cè)試一波,新增新的條件類,實(shí)現(xiàn)的matches返回false(這種寫死返回false的方法純屬測(cè)試用,沒有實(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)容器中。
到此這篇關(guān)于Spring @Conditional注解示例詳細(xì)講解的文章就介紹到這了,更多相關(guān)Spring @Conditional注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中如何使用正則表達(dá)式提取各種類型括號(hào)中的內(nèi)容
最近在工作中遇到一個(gè)問題,就是需要一個(gè)字符串中每一個(gè)中括號(hào)里的內(nèi)容,下面這篇文章主要給大家介紹了關(guān)于Java中如何使用正則表達(dá)式提取各種類型括號(hào)中的內(nèi)容,需要的朋友可以參考下2023-06-06詳解使用Mybatis-plus + velocity模板生成自定義的代碼
這篇文章主要介紹了詳解使用Mybatis-plus + velocity模板生成自定義的代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03java實(shí)現(xiàn) 微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼
這篇文章主要介紹了java實(shí)現(xiàn) 微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2016-10-10JDBC中PreparedStatement詳解以及應(yīng)用場(chǎng)景實(shí)例介紹
PreparedStatement對(duì)象代表的是一個(gè)預(yù)編譯的SQL語(yǔ)句,用它提供的setter方法可以傳入查詢的變量,這篇文章主要給大家介紹了關(guān)于JDBC中PreparedStatement詳解以及應(yīng)用場(chǎng)景實(shí)例介紹的相關(guān)資料,需要的朋友可以參考下2024-02-02Java利用位運(yùn)算實(shí)現(xiàn)比較兩個(gè)數(shù)的大小
這篇文章主要為大家介紹了,在Java中如何不用任何比較判斷符(>,==,<),返回兩個(gè)數(shù)( 32 位整數(shù))中較大的數(shù),感興趣的可以了解一下2022-08-08Java語(yǔ)法之 Java 的多態(tài)、抽象類和接口
上節(jié)介紹了 Java 基礎(chǔ)語(yǔ)法之解析 Java 的包和繼承,如果這類知識(shí)有點(diǎn)疑惑的小伙伴,可以去 Java 的包和繼承 這章看看,或許可以幫你解決一些疑惑喲!今天這篇文章我們將講解的是 Java 的多態(tài)、抽象類和接口,感興趣的小伙伴可以參考下面文章的具體內(nèi)容2021-09-09jmeter如何自動(dòng)生成測(cè)試報(bào)告
這篇文章主要介紹了jmeter如何自動(dòng)生成測(cè)試報(bào)告,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10