Spring中的@Conditional註解 詳細講解及示例

前言:

@Conditional是Spring4新提供的註解,它的作用是按照一定的條件進行判斷,滿足條件給容器註冊bean。

@Conditional的定義:

  1. //此註解可以標註在類和方法上
  2. @Target({ElementType.TYPE, ElementType.METHOD})
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. public @interface Conditional {
  6. Class<? extends Condition>[] value();
  7. }

從代碼中可以看到,需要傳入一個Class數組,並且需要繼承Condition接口:

  1. public interface Condition {
  2. boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
  3. }

Condition是個接口,需要實現matches方法,返回true則注入bean,false則不注入。

示例:

首先,創建Person類:

  1. public class Person {
  2. private String name;
  3. private Integer age;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. public Integer getAge() {
  11. return age;
  12. }
  13. public void setAge(Integer age) {
  14. this.age = age;
  15. }
  16. public Person(String name, Integer age) {
  17. this.name = name;
  18. this.age = age;
  19. }
  20. @Override
  21. public String toString() {
  22. return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
  23. }
  24. }

創建BeanConfig類,用於配置兩個Person實例並注入,一個是比爾蓋茨,一個是林納斯。

  1. @Configuration
  2. public class BeanConfig {
  3. @Bean(name = "bill")
  4. public Person person1(){
  5. return new Person("Bill Gates",62);
  6. }
  7. @Bean("linus")
  8. public Person person2(){
  9. return new Person("Linus",48);
  10. }
  11. }

接着寫一個測試類進行驗證這兩個Bean是否注入成功。

  1. public class ConditionalTest {
  2. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
  3. @Test
  4. public void test1(){
  5. Map<String, Person> map = applicationContext.getBeansOfType(Person.class);
  6. System.out.println(map);
  7. }
  8. }

 運行,輸出結果是這樣的,兩個Person實例被注入進容器。

這是一個簡單的例子,現在問題來了,如果我想根據當前操作系統來注入Person實例,windows下注入bill,linux下注入linus,怎麼實現呢?

這就需要我們用到@Conditional註解了,前言中提到,需要實現Condition接口,並重寫方法來自定義match規則。

首先,創建一個WindowsCondition類:

  1. public class WindowsCondition implements Condition {
  2. /**
  3. * @param conditionContext:判斷條件能使用的上下文環境
  4. * @param annotatedTypeMetadata:註解所在位置的註釋信息
  5. * */
  6. @Override
  7. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  8. //獲取ioc使用的beanFactory
  9. ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();
  10. //獲取類加載器
  11. ClassLoader classLoader = conditionContext.getClassLoader();
  12. //獲取當前環境信息
  13. Environment environment = conditionContext.getEnvironment();
  14. //獲取bean定義的註冊類
  15. BeanDefinitionRegistry registry = conditionContext.getRegistry();
  16. //獲得當前系統名
  17. String property = environment.getProperty("os.name");
  18. //包含Windows則說明是windows系統,返回true
  19. if (property.contains("Windows")){
  20. return true;
  21. }
  22. return false;
  23. }
  24. }

matches方法的兩個參數的意思在註釋中講述了,值得一提的是,conditionContext提供了多種方法,方便獲取各種信息,也是SpringBoot中 @ConditonalOnXX註解多樣擴展的基礎。

接着,創建LinuxCondition類:

  1. public class LinuxCondition implements Condition {
  2. @Override
  3. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  4. Environment environment = conditionContext.getEnvironment();
  5. String property = environment.getProperty("os.name");
  6. if (property.contains("Linux")){
  7. return true;
  8. }
  9. return false;
  10. }
  11. }

接着就是使用這兩個類了,因爲此註解可以標註在方法上和類上,所以分開測試:

標註在方法上:

修改BeanConfig:

  1. @Configuration
  2. public class BeanConfig {
  3. //只有一個類時,大括號可以省略
  4. //如果WindowsCondition的實現方法返回true,則注入這個bean
  5. @Conditional({WindowsCondition.class})
  6. @Bean(name = "bill")
  7. public Person person1(){
  8. return new Person("Bill Gates",62);
  9. }
  10. //如果LinuxCondition的實現方法返回true,則注入這個bean
  11. @Conditional({LinuxCondition.class})
  12. @Bean("linus")
  13. public Person person2(){
  14. return new Person("Linus",48);
  15. }
  16. }

修改測試方法,使其可以打印當前系統名:

  1. @Test
  2. public void test1(){
  3. String osName = applicationContext.getEnvironment().getProperty("os.name");
  4. System.out.println("當前系統爲:" + osName);
  5. Map<String, Person> map = applicationContext.getBeansOfType(Person.class);
  6. System.out.println(map);
  7. }

 

運行結果如下:

我是運行在windows上的所以只注入了bill,嗯,沒毛病。

接着實驗linux下的情況,不能運行在linux下,但可以修改運行時參數:

修改後啓動測試方法:

 一個方法只能注入一個bean實例,所以@Conditional標註在方法上只能控制一個bean實例是否注入。

標註在類上:

一個類中可以注入很多實例,@Conditional標註在類上就決定了一批bean是否注入。

我們試一下,將BeanConfig改寫,這時,如果WindowsCondition返回true,則兩個Person實例將被注入(注意:上一個測試將os.name改爲linux,這是我將把這個參數去掉):

  1. @Conditional({WindowsCondition.class})
  2. @Configuration
  3. public class BeanConfig {
  4. @Bean(name = "bill")
  5. public Person person1(){
  6. return new Person("Bill Gates",62);
  7. }
  8. @Bean("linus")
  9. public Person person2(){
  10. return new Person("Linus",48);
  11. }
  12. }

結果兩個實例都被注入: 

如果將類上的WindowsCondition.class改爲LinuxCondition.class,結果應該可以猜到:

結果就是空的,類中所有bean都沒有注入。

多個條件類:

前言中說,@Conditional註解傳入的是一個Class數組,存在多種條件類的情況。

這種情況貌似判斷難度加深了,測試一波,新增新的條件類,實現的matches返回false(這種寫死返回false的方法純屬測試用,沒有實際意義O(∩_∩)O)

  1. public class ObstinateCondition implements Condition {
  2. @Override
  3. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  4. return false;
  5. }
  6. }

 BeanConfig修改一下:

  1. @Conditional({WindowsCondition.class,ObstinateCondition.class})
  2. @Configuration
  3. public class BeanConfig {
  4. @Bean(name = "bill")
  5. public Person person1(){
  6. return new Person("Bill Gates",62);
  7. }
  8. @Bean("linus")
  9. public Person person2(){
  10. return new Person("Linus",48);
  11. }
  12. }

結果:

現在如果將ObstinateCondition的matches方法返回值改成true,兩個bean就被注入進容器:

結論得:

第一個條件類實現的方法返回true,第二個返回false,則結果false,不注入進容器。

第一個條件類實現的方法返回true,第二個返回true,則結果true,注入進容器中。

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章