欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring?@Conditional注解示例詳細(xì)講解

 更新時(shí)間:2022年11月07日 11:30:25   作者:阿云_  
@Conditional是Spring4新提供的注解,它的作用是按照一定的條件進(jìn)行判斷,滿足條件給容器注冊(cè)bean,這篇文章主要介紹了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)文章

最新評(píng)論