最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot自動(dòng)裝配Condition的實(shí)現(xiàn)方式

 更新時(shí)間:2021年08月02日 16:17:01   作者:張鐵牛  
這篇文章主要介紹了SpringBoot自動(dòng)裝配Condition的實(shí)現(xiàn)方式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

1. 簡(jiǎn)介

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

2. 定義

2.1 @Conditional

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

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

2.2 Condition

Condition接口定義如下:該接口為一個(gè)函數(shù)式接口,只有一個(gè)matches接口,形參為ConditionContext context, AnnotatedTypeMetadata metadata。ConditionContext定義如2.2.1,AnnotatedTypeMetadata見(jiàn)名知意,就是用來(lái)獲取注解的元信息的

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

2.2.1 ConditionContext

ConditionContext接口定義如下:通過(guò)查看源碼可以知道,從這個(gè)類(lèi)中可以獲取很多有用的信息

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();

  /**
   * 返回類(lèi)加載器
   * 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. 使用說(shuō)明

通過(guò)一個(gè)簡(jiǎn)單的小例子測(cè)試一下@Conditional是不是真的能實(shí)現(xiàn)Bean的條件化注入。

3.1 創(chuàng)建項(xiàng)目

首先我們創(chuàng)建一個(gè)SpringBoot項(xiàng)目

3.1.1 導(dǎo)入依賴(lài)

這里我們除了springboot依賴(lài),再添加個(gè)lombok依賴(lài)

<?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類(lèi)

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)建條件實(shí)現(xiàn)類(lèi)

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 修改啟動(dòng)類(lèi)

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);
      // 獲取類(lèi)型為User類(lèi)的Bean
      User user = applicationContext.getBean(User.class);
      log.info("user bean === {}", user);
   }

  /**
   * 注入U(xiǎn)ser類(lèi)型的Bean
   */
   @Bean
   @Conditional(UserCondition.class)
   public User getUser(){
      return new User("張三",18);
   }

}

3.2 測(cè)試

3.2.1 當(dāng)user.enable=false

報(bào)錯(cuò)找不到可用的User類(lèi)型的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 當(dāng)user.enable=true

正常輸出UserBean實(shí)例信息

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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 小結(jié)

上面的例子通過(guò)使用@ConditionalCondition接口,實(shí)現(xiàn)了spring bean的條件化注入。

好處:

  • 可以實(shí)現(xiàn)某些配置的開(kāi)關(guān)功能,如上面的例子,我們可以將UserBean換成開(kāi)啟緩存的配置,當(dāng)property的值為true時(shí),我們才開(kāi)啟緩存的配置。
  • 當(dāng)有多個(gè)同名的bean時(shí),如何抉擇的問(wèn)題。
  • 實(shí)現(xiàn)自動(dòng)化的裝載。如判斷當(dāng)前classpath中有mysql的驅(qū)動(dòng)類(lèi)時(shí)(說(shuō)明我們當(dāng)前的系統(tǒng)需要使用mysql),我們就自動(dòng)的讀取application.yaml中的mysql配置,實(shí)現(xiàn)自動(dòng)裝載;當(dāng)沒(méi)有驅(qū)動(dòng)時(shí),就不加載。

4. 改進(jìn)

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

4.1 創(chuàng)建注解

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

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

測(cè)試后,結(jié)果符合預(yù)期。

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

5. Spring內(nèi)置條件注解

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

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

相關(guān)文章

  • maven項(xiàng)目install時(shí)忽略執(zhí)行test方法的總結(jié)

    maven項(xiàng)目install時(shí)忽略執(zhí)行test方法的總結(jié)

    這篇文章主要介紹了maven項(xiàng)目install時(shí)忽略執(zhí)行test方法的總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 用Java實(shí)現(xiàn)連連看小游戲

    用Java實(shí)現(xiàn)連連看小游戲

    這篇文章主要為大家詳細(xì)介紹了用Java實(shí)現(xiàn)連連看小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • Spring?Cloud?Alibaba負(fù)載均衡實(shí)現(xiàn)方式

    Spring?Cloud?Alibaba負(fù)載均衡實(shí)現(xiàn)方式

    這篇文章主要為大家介紹了Spring?Cloud?Alibaba負(fù)載均衡實(shí)現(xiàn)方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • java編程題之合并兩個(gè)排序的鏈表

    java編程題之合并兩個(gè)排序的鏈表

    這篇文章主要為大家詳細(xì)介紹了java編程題之合并兩個(gè)排序的鏈表,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • java從鍵盤(pán)輸入數(shù)字并判斷大小的方法

    java從鍵盤(pán)輸入數(shù)字并判斷大小的方法

    今天小編就為大家分享一篇java從鍵盤(pán)輸入數(shù)字并判斷大小的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-07-07
  • SpringMVC和Spring的配置文件掃描包詳解

    SpringMVC和Spring的配置文件掃描包詳解

    這篇文章主要介紹了SpringMVC和Spring的配置文件掃描包,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下
    2019-05-05
  • java15新功能的詳細(xì)講解

    java15新功能的詳細(xì)講解

    這篇文章主要介紹了java15的新功能,雖然java15并不是長(zhǎng)期支持的版本,但是很多新功能還是很有用的。感興趣的小伙伴可以參考一下
    2021-08-08
  • java編程下字符串的16位,32位md5加密實(shí)現(xiàn)方法

    java編程下字符串的16位,32位md5加密實(shí)現(xiàn)方法

    下面小編就為大家?guī)?lái)一篇java編程下字符串的16位,32位md5加密實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-09-09
  • 如何使用Java?8中DateTimeFormatter類(lèi)型轉(zhuǎn)換日期格式詳解

    如何使用Java?8中DateTimeFormatter類(lèi)型轉(zhuǎn)換日期格式詳解

    這篇文章主要介紹了如何使用Java?8中DateTimeFormatter類(lèi)型轉(zhuǎn)換日期格式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • MyBatis框架簡(jiǎn)介及入門(mén)案例詳解

    MyBatis框架簡(jiǎn)介及入門(mén)案例詳解

    MyBatis是一個(gè)優(yōu)秀的持久層框架,它對(duì)jdbc的操作數(shù)據(jù)庫(kù)的過(guò)程進(jìn)行封裝,使開(kāi)發(fā)者只需要關(guān)注SQL本身,而不需要花費(fèi)精力去處理例如注冊(cè)驅(qū)動(dòng)、創(chuàng)建connection、創(chuàng)建statement、手動(dòng)設(shè)置參數(shù)、結(jié)果集檢索等jdbc繁雜的過(guò)程代碼,本文將作為最終篇為大家介紹MyBatis的使用
    2022-08-08

最新評(píng)論

溧阳市| 靖江市| 日土县| 三亚市| 永胜县| 浦城县| 奈曼旗| 万源市| 连山| 高雄县| 昌图县| 谷城县| 翼城县| 成武县| 开封市| 诏安县| 象山县| 陆河县| 凤凰县| 长葛市| 双牌县| 蒙城县| 西宁市| 沅陵县| 政和县| 曲阳县| 中卫市| 金乡县| 六盘水市| 商丘市| 四子王旗| 庆阳市| 开远市| 鹤峰县| 昌吉市| 富民县| 右玉县| 兴业县| 石家庄市| 古丈县| 宜州市|