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

SpringBoot自動裝配Condition的實現(xiàn)

 更新時間:2024年10月28日 09:05:24   作者:從零開始的-CodeNinja之路  
Spring4.0新增@Conditional注解,用于條件化Bean的注冊,通過實現(xiàn)Condition接口并重寫matches方法,可以控制Bean的創(chuàng)建與否,感興趣的可以了解一下

一、前言

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

二、 定義

2.1 @Conditional

@Conditional注解定義如下:其內(nèi)部只有一個參數(shù)為Class對象數(shù)組,且必須繼承自Condition接口,通過重寫Condition接口的matches方法來判斷是否需要加載Bean

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

2.2 Condition

Condition接口定義如下:該接口為一個函數(shù)式接口,只有一個matches接口,形參為ConditionContext context, AnnotatedTypeMetadata metadata。ConditionContext定義如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();

  /**
   * 返回環(huán)境變量 比如在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();
}

三、 使用說明

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

3.1 創(chuàng)建項目

在這里插入圖片描述

首先我們創(chuàng)建一個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 創(chuàng)建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 創(chuàng)建條件實現(xiàn)類

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)


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)

com.ldx.condition.ConditionApplication   : user bean === User(name=張三, age=18)

3.3 小結(jié)

上面的例子通過使用@Conditional和Condition接口,實現(xiàn)了spring bean的條件化注入。

好處:

  • 可以實現(xiàn)某些配置的開關(guān)功能,如上面的例子,我們可以將UserBean換成開啟緩存的配置,當property的值為true時,我們才開啟緩存的配置

  • 當有多個同名的bean時,如何抉擇的問題。

  • 實現(xiàn)自動化的裝載。如判斷當前classpath中有mysql的驅(qū)動類時(說明我們當前的系統(tǒng)需要使用mysql),我們就自動的讀取application.yaml中的mysql配置,實現(xiàn)自動裝載;當沒有驅(qū)動時,就不加載。

四、改進

從上面的使用說明中我們了解到了條件注解的大概使用方法,但是代碼中還是有很多硬編碼的問題。比如:UserCondition中的property的key包括value都是硬編碼,其實我們可以通過再擴展一個注解來實現(xiàn)動態(tài)的判斷和綁定。

4.1 創(chuàng)建注解

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

/**
 * 自定義條件屬性注解
 * <p>
 *   當配置的property name對應(yīng)的值 與設(shè)置的 value值相等時,則注入bean
 * @author ludangxin
 * @date 2021/8/1
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 指定condition的實現(xiàn)類
@Conditional({UserCondition.class})
public @interface MyConditionOnProperty {
   // 配置信息的key
   String name();
   // 配置信息key對應(yīng)的值
   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);
   }
}

測試后,結(jié)果符合預期。

其實在spring中已經(jīng)內(nèi)置了許多常用的條件注解,其中我們剛實現(xiàn)的就在內(nèi)置的注解中已經(jīng)實現(xiàn)了,如下。

五、 Spring內(nèi)置條件注解

注解 說明

  • @ConditionalOnSingleCandidate 當給定類型的bean存在并且指定為Primary的給定類型存在時,返回true
  • @ConditionalOnMissingBean 當給定的類型、類名、注解、昵稱在beanFactory中不存在時返回true.各類型間是or的關(guān)系
  • @ConditionalOnBean 與上面相反,要求bean存
  • @ConditionalOnMissingClass 當給定的類名在類路徑上不存在時返回true,各類型間是and的關(guān)系
  • @ConditionalOnClass 與上面相反,要求類存在
  • @ConditionalOnCloudPlatform 當所配置的CloudPlatform為激活時返回true
  • @ConditionalOnExpression spel表達式執(zhí)行為true
  • @ConditionalOnJava 運行時的java版本號是否包含給定的版本號.如果包含,返回匹配,否則,返回不匹配
  • @ConditionalOnProperty 要求配置屬性匹配條件 @ConditionalOnJndi 給定的jndi的Location必須存在一個.否則,返回不匹配
  • @ConditionalOnNotWebApplication web環(huán)境不存在時
  • @ConditionalOnWebApplication web環(huán)境存在時
  • @ConditionalOnResource 要求制定的資源存在

到此這篇關(guān)于 SpringBoot自動裝配Condition的實現(xiàn)的文章就介紹到這了,更多相關(guān) SpringBoot自動裝配Condition內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • SpringBoot結(jié)合Redis哨兵模式的實現(xiàn)示例

    SpringBoot結(jié)合Redis哨兵模式的實現(xiàn)示例

    這篇文章主要介紹了SpringBoot結(jié)合Redis哨兵模式的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-04-04
  • 詳解spring-boot集成elasticsearch及其簡單應(yīng)用

    詳解spring-boot集成elasticsearch及其簡單應(yīng)用

    本篇文章主要介紹了詳解spring-boot集成elasticsearch及其簡單應(yīng)用,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Mybatis-plus批量去重插入ON DUPLICATE key update使用方式

    Mybatis-plus批量去重插入ON DUPLICATE key update使用方式

    這篇文章主要介紹了Mybatis-plus批量去重插入ON DUPLICATE key update使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Maven 安裝目錄的詳細介紹

    Maven 安裝目錄的詳細介紹

    這篇文章主要介紹了Maven 安裝目錄的詳細介紹的相關(guān)資料,這里對Maven進行了解讀,希望通過本文可以幫助到大家,需要的朋友可以參考下
    2017-08-08
  • Mybatis的核心配置文件使用方法

    Mybatis的核心配置文件使用方法

    Mybatis的核心配置文件有兩個,一個是全局配置文件,它包含了會深深影響Mybatis行為的設(shè)置和屬性信息;一個是映射文件,它很簡單,讓用戶能更專注于SQL代碼,本文主要介紹了Mybatis的核心配置文件使用方法,感興趣的可以了解一下
    2023-11-11
  • SpringBoot整合MQTT小結(jié)匯總

    SpringBoot整合MQTT小結(jié)匯總

    MQTT 客戶端是運行 MQTT 庫并通過網(wǎng)絡(luò)連接到 MQTT 代理的任何設(shè)備,是一種基于發(fā)布/訂閱(publish/subscribe)模式的“輕量級”通訊協(xié)議,該協(xié)議構(gòu)建于 TCP/IP 協(xié)議上,由 IBM 于 1999 年發(fā)明,對SpringBoot整合MQTT相關(guān)知識感興趣的朋友一起看看吧
    2022-01-01
  • 一次mybatis連接查詢遇到的坑實戰(zhàn)記錄

    一次mybatis連接查詢遇到的坑實戰(zhàn)記錄

    這篇文章主要給大家介紹了關(guān)于一次mybatis連接查詢遇到的坑的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • 解決javaBean規(guī)范導致json傳參首字母大寫將永遠獲取不到問題

    解決javaBean規(guī)范導致json傳參首字母大寫將永遠獲取不到問題

    這篇文章主要介紹了解決javaBean規(guī)范導致json傳參首字母大寫將永遠獲取不到問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Thymeleaf中th:each及th:if使用方法解析

    Thymeleaf中th:each及th:if使用方法解析

    這篇文章主要介紹了Thymeleaf中th:each及th:if使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • Java代碼精簡之道(推薦)

    Java代碼精簡之道(推薦)

    這篇文章主要給大家介紹了Java代碼精簡之道,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11

最新評論