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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/13846.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

优惠券平台(十一):布隆过滤器、缓存空值、分布式组合的双重判定锁解决缓存穿透问题

业务背景 在上一节中&#xff0c;我们讨论了正常用户在访问优惠券时可能遇到的缓存击穿问题&#xff0c;并介绍了缓存预热、缓存永不过期、分布式锁、双重判定锁、分片分布式锁等技术来应对这些问题。然而&#xff0c;还有一个问题需要解决&#xff1a;如果用户频繁访问数据库…

VUE 集成企微机器人通知

message-robot 便于线上异常问题及时发现处理&#xff0c;项目中集成企微机器人通知&#xff0c;及时接收问题并处理 企微机器人通知工具类 export class MessageRobotUtil {constructor() {}/*** 发送 markdown 消息* param robotKey 机器人 ID* param title 消息标题* param…

阿里云cdn怎样设置图片压缩

阿里云 CDN 提供了图像加速服务&#xff0c;其中包括图像压缩功能。通过设置图片压缩&#xff0c;可以显著减小图片文件的体积&#xff0c;提升网站加载速度&#xff0c;同时减少带宽消耗。九河云来告诉你如何进行图片压缩吧。 如何设置阿里云 CDN 图片压缩&#xff1f; 1. 登…

GB/T28181 开源日记[8]:国标开发速知速会

服务端源代码 github.com/gowvp/gb28181 前端源代码 github.com/gowvp/gb28181_web 介绍 go wvp 是 Go 语言实现的开源 GB28181 解决方案&#xff0c;基于GB28181-2022标准实现的网络视频平台&#xff0c;支持 rtmp/rtsp&#xff0c;客户端支持网页版本和安卓 App。支持rts…

初窥强大,AI识别技术实现图像转文字(OCR技术)

⭐️⭐️⭐️⭐️⭐️欢迎来到我的博客⭐️⭐️⭐️⭐️⭐️ &#x1f434;作者&#xff1a;秋无之地 &#x1f434;简介&#xff1a;CSDN爬虫、后端、大数据、人工智能领域创作者。目前从事python全栈、爬虫和人工智能等相关工作&#xff0c;主要擅长领域有&#xff1a;python…

如何在Docker中运行MySQL容器?

随着容器化技术的普及&#xff0c;Docker已成为开发和部署应用的首选工具之一。MySQL作为最流行的开源关系型数据库&#xff0c;也非常适合在Docker容器中运行。本文将介绍如何在Docker中运行MySQL容器&#xff0c;帮助你快速搭建一个可用的数据库环境。 1. 安装Docker 首先&a…

[ESP32:Vscode+PlatformIO]添加第三方库 开源库 与Arduino导入第三方库的区别

前言 PlatformIO与Arduino在添加第三方库方面的原理存在显著差异 在PlatformIO中&#xff0c;第三方库的使用是基于项目&#xff08;工程&#xff09;的。具体而言&#xff0c;只有当你为一个特定的项目添加了某个第三方库后&#xff0c;该项目才能使用该库。这些第三方库的文…

高端入门:Ollama 本地高效部署DeepSeek模型深度搜索解决方案

目录 一、Ollama 介绍 二、Ollama下载 2.1 官网下载 2.2 GitHub下载 三、模型库 四、Ollmal 使用 4.1 模型运行&#xff08;下载&#xff09; 4.2 模型提问 五、Ollama 常用命令 相关推荐 一、Ollama 介绍 Ollama是一个专为在本地机器上便捷部署和运行大型语言模型&…

【DeepSeek论文精读】2. DeepSeek LLM:以长期主义扩展开源语言模型

欢迎关注[【youcans的AGI学习笔记】](https://blog.csdn.net/youcans/category_12244543.html&#xff09;原创作品 【DeepSeek论文精读】1. 从 DeepSeek LLM 到 DeepSeek R1 【DeepSeek论文精读】2. DeepSeek LLM&#xff1a;以长期主义扩展开源语言模型 【DeepSeek论文精读】…

力扣.623. 在二叉树中增加一行(链式结构的插入操作)

Problem: 623. 在二叉树中增加一行 文章目录 题目描述思路复杂度Code 题目描述 思路 1.首先要说明&#xff0c;对于数据结构无非两大类结构&#xff1a;顺序结构、链式结构&#xff0c;而二叉树实质上就可以等效看作为一个二叉链表&#xff0c;而对于链表插入一个节点的操作是应…

深度学习01 神经网络

深度学习是机器学习领域中的一个新的研究方向。所以在学习深度学习之前我们需要了解一下神经网络。 神经网络 神经网络:是由大量的节点&#xff08;或称“神经元”&#xff09;和之间相互的联接构成。 每个节点代表一种特定的输出函数&#xff0c;称为激励函数、激活函数&…

基于JUnit4和JUnit5配合例子讲解JUnit的两种运行方式

1 引言 最近读的书有老有新&#xff0c;在读的过程中都完全完成了相应例子的构建和运行。在读《Spring in Action》1第4版时&#xff0c;其第37页的例子&#xff08;以下称例子1&#xff09;基于JUnit 4&#xff0c;并需要spring-test.jar&#xff1b;而在读《JUnit in Action…

【提示词工程】探索大语言模型的参数设置:优化提示词交互的技巧

在与大语言模型(Large Language Model, LLM)进行交互时,提示词的设计和参数设置直接影响生成内容的质量和效果。无论是通过 API 调用还是直接使用模型,掌握模型的参数配置方法都至关重要。本文将为您详细解析常见的参数设置及其应用场景,帮助您更高效地利用大语言模型。 …

使用Python创建、读取和修改Word文档

自动化文档处理是提升工作效率的关键路径之一&#xff0c;而Python凭借其简洁语法和丰富的生态工具链&#xff0c;是实现文档自动化处理的理想工具。通过编程手段批量生成结构规范的合同模板、动态注入数据分析结果生成可视化报告&#xff0c;或是快速提取海量文档中的关键信息…

Android Studio 2024.2.2.13版本安装配置详细教程

Android Studio 是由 Google 官方开发和维护的集成开发环境&#xff08;IDE&#xff09;&#xff0c;专为 Android 应用开发设计。它是基于 JetBrains 的 IntelliJ IDEA 平台构建的&#xff0c;集成了丰富的工具和功能&#xff0c;帮助开发者高效构建、调试、测试和发布 Androi…

Qt实现简易音乐播放器

使用Qt6实现简易音乐播放器&#xff0c;效果如下&#xff1a; github&#xff1a; Gabriel-gxb/MusicPlayer: qt6实现简易音乐播放器 一、整体架构 基于Qt框架构建 整个音乐播放器程序以Qt框架为基础进行开发。Qt提供了丰富的类库和工具&#xff0c;方便开发者构建图形用户界…

GPT-4使用次数有上限吗?一文了解使用规则

GPT-4的推出&#xff0c;让越来越多的用户开始体验其卓越的功能。无论是用于日常需求还是专业内容制作&#xff0c;GPT-4的应用范围广泛&#xff0c;获得了用户的广泛赞誉。但是&#xff0c;在具体使用过程中&#xff0c;不少用户发现自己似乎触碰到了GPT-4的使用上限&#xff…

水波效果

水波效果指在计算机图形学中模拟水面波纹的视觉效果&#xff0c;通常用于游戏、动画或者其他虚拟场景中。主要用于体现水体的动态感&#xff0c;比如水的波动、反射、折射、透明等&#xff0c;可以让人感觉像真实的水一样流动闪耀。 核心特点就是&#xff1a; 动态波纹光学特…

Redis | 十大数据类型

文章目录 十大数据类型概述key操作命令数据类型命令及落地运用redis字符串&#xff08;String&#xff09;redis列表&#xff08;List&#xff09;redis哈希表&#xff08;Hash&#xff09;redis集合&#xff08;Set&#xff09;redis有序集合&#xff08;ZSet / SortedSet&…

Linux之安装docker

一、检查版本和内核是否合格 Docker支持64位版本的CentOS 7和CentOS 8及更高版本&#xff0c;它要求Linux内核版本不低于3.10。 检查版本 cat /etc/redhat-release检查内核 uname -r二、Docker的安装 1、自动安装 Docker官方和国内daocloud都提供了一键安装的脚本&#x…