1. 程式人生 > 其它 >SpringBoot自動裝配-Condition

SpringBoot自動裝配-Condition

1. 簡介

@Conditional註解在Spring4.0中引入,其主要作用就是判斷條件是否滿足,從而決定是否初始化並向容器註冊Bean。

2. 定義

2.1 @Conditional

@Conditional註解定義如下:其內部只有一個引數為Class物件陣列,且必須繼承自Condition介面,通過重寫Condition介面的matches方法來判斷是否需要載入Bean

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
  Class<? extends Condition>[] value();
}

2.2 Condition

Condition介面定義如下:該介面為一個函式式介面,只有一個matches介面,形參為ConditionContext context, AnnotatedTypeMetadata metadataConditionContext定義如2.2.1,AnnotatedTypeMetadata見名知意,就是用來獲取註解的元資訊的

@FunctionalInterface
public interface Condition {
  boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}

2.2.1 ConditionContext

ConditionContext介面定義如下:通過檢視原始碼可以知道,從這個類中可以獲取很多有用的資訊

public interface ConditionContext {
  /**
   * 返回Bean定義資訊
   * Return the {@link BeanDefinitionRegistry} that will hold the bean definition
   * should the condition match.
   * @throws IllegalStateException if no registry is available (which is unusual:
   * only the case with a plain {@link ClassPathScanningCandidateComponentProvider})
   */
  BeanDefinitionRegistry getRegistry();

  /**
   * 返回Bean工廠
   * Return the {@link ConfigurableListableBeanFactory} that will hold the bean
   * definition should the condition match, or {@code null} if the bean factory is
   * not available (or not downcastable to {@code ConfigurableListableBeanFactory}).
   */
  @Nullable
  ConfigurableListableBeanFactory getBeanFactory();

  /**
   * 返回環境變數 比如在application.yaml中定義的資訊
   * Return the {@link Environment} for which the current application is running.
   */
  Environment getEnvironment();

  /**
   * 返回資源載入器
   * Return the {@link ResourceLoader} currently being used.
   */
  ResourceLoader getResourceLoader();

  /**
   * 返回類載入器
   * Return the {@link ClassLoader} that should be used to load additional classes
   * (only {@code null} if even the system ClassLoader isn't accessible).
   * @see org.springframework.util.ClassUtils#forName(String, ClassLoader)
   */
  @Nullable
  ClassLoader getClassLoader();
}

3. 使用說明

通過一個簡單的小例子測試一下@Conditional是不是真的能實現Bean的條件化注入。

3.1 建立專案

首先我們建立一個SpringBoot專案

3.1.1 匯入依賴

這裡我們除了springboot依賴,再添加個lombok依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ldx</groupId>
    <artifactId>condition</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>condition</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3.1.2 新增配置資訊

在application.yaml 中加入配置資訊

user:
  enable: false

3.1.3 建立User類

package com.ldx.condition;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 使用者資訊
 * @author ludangxin
 * @date 2021/8/1
 */
@Data
@AllArgsConstructor
public class User {
   private String name;
   private Integer age;
}

3.1.4 建立條件實現類

package com.ldx.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * 使用者bean條件判斷
 * @author ludangxin
 * @date 2021/8/1
 */
public class UserCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
      Environment environment = conditionContext.getEnvironment();
      // 獲取property user.enable
      String property = environment.getProperty("user.enable");
      // 如果user.enable的值等於true 那麼返回值為true,反之為false
      return "true".equals(property);
   }
}

3.1.5 修改啟動類

package com.ldx.condition;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;

@Slf4j
@SpringBootApplication
public class ConditionApplication {

   public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(ConditionApplication.class, args);
      // 獲取型別為User類的Bean
      User user = applicationContext.getBean(User.class);
      log.info("user bean === {}", user);
   }

  /**
   * 注入User型別的Bean
   */
   @Bean
   @Conditional(UserCondition.class)
   public User getUser(){
      return new User("張三",18);
   }

}

3.2 測試

3.2.1 當user.enable=false

報錯找不到可用的User型別的Bean

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.3)

2021-08-01 17:07:51.994  INFO 47036 --- [           main] com.ldx.condition.ConditionApplication   : Starting ConditionApplication using Java 1.8.0_261 on ludangxindeMacBook-Pro.local with PID 47036 (/Users/ludangxin/workspace/idea/condition/target/classes started by ludangxin in /Users/ludangxin/workspace/idea/condition)
2021-08-01 17:07:51.997  INFO 47036 --- [           main] com.ldx.condition.ConditionApplication   : No active profile set, falling back to default profiles: default
2021-08-01 17:07:52.461  INFO 47036 --- [           main] com.ldx.condition.ConditionApplication   : Started ConditionApplication in 0.791 seconds (JVM running for 1.371)
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ldx.condition.User' available
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172)
	at com.ldx.condition.ConditionApplication.main(ConditionApplication.java:16)

Process finished with exit code 1

3.2.2 當user.enable=true

正常輸出UserBean例項資訊

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.3)

2021-08-01 17:13:38.022  INFO 47129 --- [           main] com.ldx.condition.ConditionApplication   : Starting ConditionApplication using Java 1.8.0_261 on ludangxindeMacBook-Pro.local with PID 47129 (/Users/ludangxin/workspace/idea/condition/target/classes started by ludangxin in /Users/ludangxin/workspace/idea/condition)
2021-08-01 17:13:38.024  INFO 47129 --- [           main] com.ldx.condition.ConditionApplication   : No active profile set, falling back to default profiles: default
2021-08-01 17:13:38.434  INFO 47129 --- [           main] com.ldx.condition.ConditionApplication   : Started ConditionApplication in 0.711 seconds (JVM running for 1.166)
2021-08-01 17:13:38.438  INFO 47129 --- [           main] com.ldx.condition.ConditionApplication   : user bean === User(name=張三, age=18)

3.3 小結

上面的例子通過使用@ConditionalCondition介面,實現了spring bean的條件化注入。

好處:

  1. 可以實現某些配置的開關功能,如上面的例子,我們可以將UserBean換成開啟快取的配置,當property的值為true時,我們才開啟快取的配置。
  2. 當有多個同名的bean時,如何抉擇的問題。
  3. 實現自動化的裝載。如判斷當前classpath中有mysql的驅動類時(說明我們當前的系統需要使用mysql),我們就自動的讀取application.yaml中的mysql配置,實現自動裝載;當沒有驅動時,就不載入。

4. 改進

從上面的使用說明中我們瞭解到了條件註解的大概使用方法,但是程式碼中還是有很多硬編碼的問題。比如:UserCondition中的property的key包括value都是硬編碼,其實我們可以通過再擴充套件一個註解來實現動態的判斷和繫結。

4.1 建立註解

import org.springframework.context.annotation.Conditional;
import java.lang.annotation.*;

/**
 * 自定義條件屬性註解
 * <p>
 *   當配置的property name對應的值 與設定的 value值相等時,則注入bean
 * @author ludangxin
 * @date 2021/8/1
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 指定condition的實現類
@Conditional({UserCondition.class})
public @interface MyConditionOnProperty {
   // 配置資訊的key
   String name();
   // 配置資訊key對應的值
   String value();
}

4.2 修改UserCondition

package com.ldx.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * 使用者bean條件判斷
 * @author ludangxin
 * @date 2021/8/1
 */
public class UserCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
      Environment environment = conditionContext.getEnvironment();
      // 獲取自定義的註解
      Map<String, Object> annotationAttributes = annotatedTypeMetadata.getAnnotationAttributes("com.ldx.condition.MyConditionOnProperty");
      // 獲取在註解中指定的name的property的值 如:user.enable的值
      String property = environment.getProperty(annotationAttributes.get("name").toString());
      // 獲取預期的值
      String value = annotationAttributes.get("value").toString();
      return value.equals(property);
   }
}

測試後,結果符合預期。

其實在spring中已經內建了許多常用的條件註解,其中我們剛實現的就在內建的註解中已經實現了,如下。

5. Spring內建條件註解

註解 說明
@ConditionalOnSingleCandidate 當給定型別的bean存在並且指定為Primary的給定型別存在時,返回true
@ConditionalOnMissingBean 當給定的型別、類名、註解、暱稱在beanFactory中不存在時返回true.各型別間是or的關係
@ConditionalOnBean 與上面相反,要求bean存在
@ConditionalOnMissingClass 當給定的類名在類路徑上不存在時返回true,各型別間是and的關係
@ConditionalOnClass 與上面相反,要求類存在
@ConditionalOnCloudPlatform 當所配置的CloudPlatform為啟用時返回true
@ConditionalOnExpression spel表示式執行為true
@ConditionalOnJava 執行時的java版本號是否包含給定的版本號.如果包含,返回匹配,否則,返回不匹配
@ConditionalOnProperty 要求配置屬性匹配條件
@ConditionalOnJndi 給定的jndi的Location 必須存在一個.否則,返回不匹配
@ConditionalOnNotWebApplication web環境不存在時
@ConditionalOnWebApplication web環境存在時
@ConditionalOnResource 要求制定的資源存在