【Spring Boot】 SpringBoot自动装配-Condition

2024-09-08 04:28

本文主要是介绍【Spring Boot】 SpringBoot自动装配-Condition,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

    • 一、前言
    • 二、 定义
      • 2.1 @Conditional
      • 2.2 Condition
      • 2.2.1 ConditionContext
    • 三、 使用说明
      • 3.1 创建项目
        • 3.1.1 导入依赖
        • 3.1.2 添加配置信息
        • 3.1.3 创建User类
        • 3.1.4 创建条件实现类
        • 3.1.5 修改启动类
      • 3.2 测试
        • 3.2.1 当user.enable=false
        • 3.2.2 当user.enable=true
      • 3.3 小结
    • 四、改进
      • 4.1 创建注解
      • 4.2 修改UserCondition
    • 五、 Spring内置条件注解

在这里插入图片描述
在这里插入图片描述

一、前言

@Conditional注解在Spring4.0中引入,其主要作用就是判断条件是否满足,从而决定是否初始化并向容器注册Bean。

二、 定义

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 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}).*/@NullableConfigurableListableBeanFactory 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)*/@NullableClassLoader getClassLoader();
}

三、 使用说明

通过一个简单的小例子测试一下@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 {@Overridepublic boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {Environment environment = conditionContext.getEnvironment();// 获取property user.enableString property = environment.getProperty("user.enable");// 如果user.enable的值等于true 那么返回值为true,反之为falsereturn "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类的BeanUser 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' availableat 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 小结

上面的例子通过使用@Conditional和Condition接口,实现了spring bean的条件化注入。

好处:

  1. 可以实现某些配置的开关功能,如上面的例子,我们可以将UserBean换成开启缓存的配置,当property的值为true时,我们才开启缓存的配置

  2. 当有多个同名的bean时,如何抉择的问题。

  3. 实现自动化的装载。如判断当前classpath中有mysql的驱动类时(说明我们当前的系统需要使用mysql),我们就自动的读取application.yaml中的mysql配置,实现自动装载;当没有驱动时,就不加载。

四、改进

从上面的使用说明中我们了解到了条件注解的大概使用方法,但是代码中还是有很多硬编码的问题。比如: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 {// 配置信息的keyString 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 {@Overridepublic 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中已经内置了许多常用的条件注解,其中我们刚实现的就在内置的注解中已经实现了,如下。

五、 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 要求制定的资源存在

这篇关于【Spring Boot】 SpringBoot自动装配-Condition的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147105

相关文章

Java程序进程起来了但是不打印日志的原因分析

《Java程序进程起来了但是不打印日志的原因分析》:本文主要介绍Java程序进程起来了但是不打印日志的原因分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java程序进程起来了但是不打印日志的原因1、日志配置问题2、日志文件权限问题3、日志文件路径问题4、程序

Spring 基于XML配置 bean管理 Bean-IOC的方法

《Spring基于XML配置bean管理Bean-IOC的方法》:本文主要介绍Spring基于XML配置bean管理Bean-IOC的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录一. spring学习的核心内容二. 基于 XML 配置 bean1. 通过类型来获取 bean2. 通过

Spring Boot 集成 Quartz并使用Cron 表达式实现定时任务

《SpringBoot集成Quartz并使用Cron表达式实现定时任务》本篇文章介绍了如何在SpringBoot中集成Quartz进行定时任务调度,并通过Cron表达式控制任务... 目录前言1. 添加 Quartz 依赖2. 创建 Quartz 任务3. 配置 Quartz 任务调度4. 启动 Sprin

springboot上传zip包并解压至服务器nginx目录方式

《springboot上传zip包并解压至服务器nginx目录方式》:本文主要介绍springboot上传zip包并解压至服务器nginx目录方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录springboot上传zip包并解压至服务器nginx目录1.首先需要引入zip相关jar包2.然

Java数组初始化的五种方式

《Java数组初始化的五种方式》数组是Java中最基础且常用的数据结构之一,其初始化方式多样且各具特点,本文详细讲解Java数组初始化的五种方式,分析其适用场景、优劣势对比及注意事项,帮助避免常见陷阱... 目录1. 静态初始化:简洁但固定代码示例核心特点适用场景注意事项2. 动态初始化:灵活但需手动管理代

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

将Java项目提交到云服务器的流程步骤

《将Java项目提交到云服务器的流程步骤》所谓将项目提交到云服务器即将你的项目打成一个jar包然后提交到云服务器即可,因此我们需要准备服务器环境为:Linux+JDK+MariDB(MySQL)+Gi... 目录1. 安装 jdk1.1 查看 jdk 版本1.2 下载 jdk2. 安装 mariadb(my

SpringBoot中配置Redis连接池的完整指南

《SpringBoot中配置Redis连接池的完整指南》这篇文章主要为大家详细介绍了SpringBoot中配置Redis连接池的完整指南,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以... 目录一、添加依赖二、配置 Redis 连接池三、测试 Redis 操作四、完整示例代码(一)pom.

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm