Spring注解@Conditional案例解析
【1】@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則不注入。
【2】@Conditional示例
首先,創(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)建MyConfig類,用于配置兩個(gè)Person實(shí)例并注入,一個(gè)是Bill Gates,一個(gè)是linus。
@Configuration
public class MyConfig {
@Bean(name = "bill")
public Person person1(){
return new Person("Bill Gates",62);
}
@Bean("linus")
public Person person2(){
return new Person("Linus",48);
}
}
寫一個(gè)測(cè)試類,測(cè)試是否注入成功
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);
}
}
/**測(cè)試結(jié)果
{bill=Person{name='Bill Gates',age=62},linus=Person{name='Linus',age='48'}}
*/
這是一個(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;
}
}
接著,創(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;
}
}
修改MyConfig:
@Configuration
public class MyConfig {
//只有一個(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);
}
}
標(biāo)注在方法上:
修改測(cè)試程序,開始測(cè)試:
public class ConditionalTest {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
@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);
}
}
/**測(cè)試結(jié)果
當(dāng)前系統(tǒng)為:Windows 10
{bill=Person{name='Bill Gates',age=62}}
*/
一個(gè)方法只能注入一個(gè)bean實(shí)例,所以@Conditional標(biāo)注在方法上只能控制一個(gè)bean實(shí)例是否注入
標(biāo)注在類上:
@Configuration
@Conditional({WindowsCondition.class})
public class MyConfig {
//只有一個(gè)類時(shí),大括號(hào)可以省略
//如果WindowsCondition的實(shí)現(xiàn)方法返回true,則注入這個(gè)bean
@Bean(name = "bill")
public Person person1(){
return new Person("Bill Gates",62);
}
//如果LinuxCondition的實(shí)現(xiàn)方法返回true,則注入這個(gè)bean
@Bean("linus")
public Person person2(){
return new Person("Linus",48);
}
}
一個(gè)類中可以注入很多實(shí)例,@Conditional標(biāo)注在類上就決定了一批bean是否注入。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot中使用Spring-Retry重試框架的實(shí)現(xiàn)
本文主要介紹了Spring Boot中使用Spring-Retry重試框架的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
Spring?boot事務(wù)無效報(bào)錯(cuò):Transaction?not?enabled問題排查解決
在業(yè)務(wù)代碼中經(jīng)常需要保證事務(wù)的原子性,但是有的時(shí)候確實(shí)是出現(xiàn)事務(wù)沒有生效,這篇文章主要給大家介紹了關(guān)于Spring?boot事務(wù)無效報(bào)錯(cuò):Transaction?not?enabled問題排查的相關(guān)資料,需要的朋友可以參考下2023-11-11
SPRINGBOOT讀取PROPERTIES配置文件數(shù)據(jù)過程詳解
這篇文章主要介紹了SPRINGBOOT讀取PROPERTIES配置文件數(shù)據(jù)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
java同步器AQS架構(gòu)AbstractQueuedSynchronizer原理解析
這篇文章主要為大家介紹了java同步器AQS架構(gòu)AbstractQueuedSynchronizer的底層原理及源碼解析,有需要的朋友可以借鑒參考下,希望能有所幫助,祝大家多多進(jìn)步早日升職加薪2022-03-03
一文搞懂JMeter engine中HashTree的配置問題
本文主要介紹了JMeter engine中HashTree的配置,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09

