当前位置: 首页 > news >正文

SpringBoot 自动配置

Condition

自定义条件:

  • 定义条件类:自定义类实现Condition接口,重写 matches 方法,在 matches 方法中进行逻辑判断,返回boolean值 。 matches 方法两个参数:
    • context:上下文对象,可以获取属性值,获取类加载器,获取BeanFactory等。
    • metadata:元数据对象,用于获取注解属性。
  • 判断条件: 在初始化Bean时,使用 @Conditional(条件类.class)注解

SpringBoot 提供的常用条件注解:

  • ConditionalOnProperty:判断配置文件中是否有对应属性和值才初始化Bean
  • ConditionalOnClass:判断环境中是否有对应字节码文件才初始化Bean
  • ConditionalOnMissingBean:判断环境中没有对应Bean才初始化Bean

示例1:导入Jedis坐标后,加载该Bean,没导入,则不加载

public class User {
}
public class Role {
}
@Configuration
public class UserConfig {@Bean@Conditional(ClassCondition.class)public User user(){return new User();}
}
public class ClassCondition implements Condition {/**** @param context 上下文对象。用于获取环境,IOC容器,ClassLoader对象* @param metadata 注解元对象。 可以用于获取注解定义的属性值* @return*/@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {//1.需求: 导入Jedis坐标后创建Bean//思路:判断redis.clients.jedis.Jedis.class文件是否存在boolean flag = true;try {Class<?> cls = Class.forName("redis.clients.jedis.Jedis");} catch (ClassNotFoundException e) {flag = false;}return flag;}
@SpringBootApplication
public class SpringbootConditionApplication {public static void main(String[] args) {//启动SpringBoot的应用,返回Spring的IOC容器ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args);Object user = context.getBean("user");System.out.println(user);}}

示例2:将类的判断定义为动态的。判断哪个字节码文件存在可以动态指定

@Configuration
public class UserConfig {@Bean@ConditionOnClass("redis.clients.jedis.Jedis")public User user(){return new User();}}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassCondition.class)
public @interface ConditionOnClass {String[] value();
}
public class ClassCondition implements Condition {/**** @param context 上下文对象。用于获取环境,IOC容器,ClassLoader对象* @param metadata 注解元对象。 可以用于获取注解定义的属性值* @return*/@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {//获取注解属性值  valueMap<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());//System.out.println(map);String[] value = (String[]) map.get("value");boolean flag = true;try {for (String className : value) {Class<?> cls = Class.forName(className);}} catch (ClassNotFoundException e) {flag = false;}return flag;}
}

示例3:ConditionalOnProperty配置作用

@Configuration
public class UserConfig {@Bean@ConditionalOnProperty(name = "spring",havingValue = "zhangsan")public User user(){return new User();}}

application.properties

spring=zhagnsan

@Import注解

@Enable*底层依赖于@Import注解导入一些类,使用@Import导入的类会被Spring加载到IOC容器中。而@Import提供4中用法:

  • 导入Bean
  • 导入配置类
  • 导入 ImportSelector 实现类。一般用于加载配置文件中的类
  • 导入 ImportBeanDefinitionRegistrar 实现类。

示例0:Enable

@EnableUser
@SpringBootApplication
public class SpringbootEnableApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);//获取BeanObject user = context.getBean("user");System.out.println(user);}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(UserConfig.class)
public @interface EnableUser {
}
public class UserConfig {@Beanpublic User user() {return new User();}@Beanpublic Role role() {return new Role();}
}

示例一:导入Bean

@Import(User.class)
@SpringBootApplication
public class SpringbootEnableApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);User user = context.getBean(User.class);System.out.println(user);
}

示例二:导入配置类

public class UserConfig {@Beanpublic User user() {return new User();}@Beanpublic Role role() {return new Role();}
}
@Import(UserConfig.class)
@SpringBootApplication
public class SpringbootEnableApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);User user = context.getBean(User.class);System.out.println(user);Role role = context.getBean(Role.class);System.out.println(role);
}

示例3:导入ImportSelector的实现类

public class MyImportSelector implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {return new String[]{"com.release.domain.User", "com.release.domain.Role"};}
}
@Import(MyImportSelector.class)
@SpringBootApplication
public class SpringbootEnableApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);User user = context.getBean(User.class);System.out.println(user);Role role = context.getBean(Role.class);System.out.println(role);
}

示例4:导入 ImportBeanDefinitionRegistrar 实现类

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition();registry.registerBeanDefinition("user", beanDefinition);}
}
@Import({MyImportBeanDefinitionRegistrar.class})
@SpringBootApplication
public class SpringbootEnableApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);Object user = context.getBean("user");System.out.println(user);Map<String, User> map = context.getBeansOfType(User.class);System.out.println(map);
}

@EnableAutoConfiguration 注解

  • @EnableAutoConfiguration 注解内部使用 @Import(AutoConfigurationImportSelector.class)来加载配置类。

  • 配置文件位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当 SpringBoot 应用启动时,会自动加载这些配置类,初始化Bean

  • 并不是所有的Bean都会被初始化,在配置类中使用Condition来加载满足条件的Bean

示例:自定义redis-starter。要求当导入redis坐标时,SpringBoot自动创建Jedis的Bean。
实现步骤:

  • 1.创建 redis-spring-boot-autoconfigure 模块
  • 2.创建 redis-spring-boot-starter 模块,依赖 redis-spring-boot-autoconfigure的模块
  • 3.在 redis-spring-boot-autoconfigure 模块中初始化 Jedis 的 Bean。并定义META-INF/spring.factories 文件
  • 4.在测试模块中引入自定义的 redis-starter 依赖,测试获取 Jedis 的Bean,操作 redis。

3.在 redis-spring-boot-autoconfigure 模块中初始化 Jedis 的 Bean。并定义META-INF/spring.factories 文件

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
@ConditionalOnClass(Jedis.class)
public class RedisAutoConfiguration {/*** 提供Jedis的bean*/@Bean@ConditionalOnMissingBean(name = "jedis")public Jedis jedis(RedisProperties redisProperties) {System.out.println("RedisAutoConfiguration....");return new Jedis(redisProperties.getHost(), redisProperties.getPort());}
}
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {private String host = "localhost";private int port = 6379;public String getHost() {return host;}public void setHost(String host) {this.host = host;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}
}

META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.release.redis.config.RedisAutoConfiguration

4.在测试模块中引入自定义的 redis-starter 依赖,测试获取 Jedis 的Bean,操作 redis。

@SpringBootApplication
public class SpringbootEnableApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);Jedis jedis = context.getBean(Jedis.class);System.out.println(jedis);@Beanpublic Jedis jedis(){return  new  Jedis("123.56.72.62",6379);}}

相关文章:

SpringBoot 自动配置

Condition 自定义条件&#xff1a; 定义条件类&#xff1a;自定义类实现Condition接口&#xff0c;重写 matches 方法&#xff0c;在 matches 方法中进行逻辑判断&#xff0c;返回boolean值 。 matches 方法两个参数&#xff1a; context&#xff1a;上下文对象&#xff0c;可…...

IP-guard WebServer 远程命令执行漏洞

IP-guard WebServer 远程命令执行漏洞 免责声明漏洞描述漏洞影响漏洞危害网络测绘Fofa: app"ip-guard" 漏洞复现1. 构造poc2. 访问文件3. 执行命令 免责声明 仅用于技术交流,目的是向相关安全人员展示漏洞利用方式,以便更好地提高网络安全意识和技术水平。 任何人不…...

每次重启完IDEA,application.properties文件里的中文变成?

出现这种情况&#xff0c;在IDEA打开Settings-->Editor-->File Encodings 然后&#xff0c;你需要将问号改为你需要的汉字。 重启IDEA&#xff0c;再次查看你的.properties文件就会发现再没有变成问号了...

【Truffle】四、通过Ganache部署连接

目录 一、下载安装 Ganache&#xff1a; 二、在本地部署truffle 三、配置ganache连接truffle 四、交易发送 除了用Truffle Develop&#xff0c;还可以选择使用 Ganache, 这是一个桌面应用&#xff0c;他同样会创建一个个人模拟的区块链。 对于刚接触以太坊的同学来说&#x…...

React 其他常用Hooks

1. useImperativeHandle 在react中父组件可以通过forwardRef将ref转发到子组件&#xff1b;子组件拿到父组件创建的ref&#xff0c;绑定到自己的某个元素&#xff1b; forwardRef的做法本身没有什么问题&#xff0c;但是我们是将子组件的DOM直接暴露给了父组件&#xff0c;某下…...

将 ONLYOFFICE 文档编辑器与 С# 群件平台集成

在本文中&#xff0c;我们会向您展示 ONLYOFFICE 文档编辑器与其自有的协作平台集成。 ONLYOFFICE 是一款开源办公套件&#xff0c;包括文本文档、电子表格和演示文稿编辑器。这款套件支持用户通过文档编辑组件扩展第三方 web 应用的功能&#xff0c;可直接在应用的界面中使用。…...

使用电脑时提示msvcp140.dll丢失的5个解决方法

“计算机中msvcp140.dll丢失的5个解决方法”。在我们日常使用电脑的过程中&#xff0c;有时会遇到一些错误提示&#xff0c;其中之一就是“msvcp140.dll丢失”。那么&#xff0c;什么是msvcp140.dll呢&#xff1f;它的作用是什么&#xff1f;丢失它会对电脑产生什么影响呢&…...

VR全景如何应用在房产行业,VR看房有哪些优势

导语&#xff1a; 在如今的数字时代&#xff0c;虚拟现实&#xff08;VR&#xff09;技术的迅猛发展为许多行业带来了福音&#xff0c;特别是在房产楼盘行业中。通过利用VR全景技术&#xff0c;开发商和销售人员可以为客户提供沉浸式的楼盘浏览体验&#xff0c;从而带来诸多优…...

11月份 四川汽车托运报价已经上线

中国人不骗中国人!! 国庆小长假的高峰期过后 放假综合症的你还没痊愈吧 今天给大家整理了9条最新线路 广州到四川的托运单价便宜到&#x1f4a5; 核算下来不过几毛钱&#x1f4b0; 相比起自驾的漫长和疲惫&#x1f697; 托运不得不说真的很省事 - 赠送保险 很多客户第一次运车 …...

springcloud图书借阅管理系统源码

开发说明&#xff1a; jdk1.8&#xff0c;mysql5.7&#xff0c;nodejs&#xff0c;idea&#xff0c;nodejs&#xff0c;vscode springcloud springboot mybatis vue elementui 功能介绍&#xff1a; 用户端&#xff1a; 登录注册 首页显示搜索图书&#xff0c;轮播图&…...

主题模型LDA教程:LDA主题数选取:困惑度preplexing

文章目录 LDA主题数困惑度1.概率分布的困惑度2.概率模型的困惑度3.每个分词的困惑度 LDA主题数 LDA作为一种无监督学习方法&#xff0c;类似于k-means聚类算法&#xff0c;需要给定超参数主题数K&#xff0c;但如何评价主题数的优劣并无定论&#xff0c;一般采取人为干预、主题…...

Docker快速入门

Docker是一个用来快速构建、运行和管理应用的工具。 Docker技术能够避免对服务器环境的依赖&#xff0c;减少复杂的部署流程&#xff0c;有了Docker以后&#xff0c;可以实现一键部署&#xff0c;项目的部署如丝般顺滑&#xff0c;大大减少了运维工作量。 即使你对Linux不熟…...

36 Gateway网关 快速入门

3.Gateway服务网关 Spring Cloud Gateway 是 Spring Cloud 的一个全新项目&#xff0c;该项目是基于 Spring 5.0&#xff0c;Spring Boot 2.0 和 Project Reactor 等响应式编程和事件流技术开发的网关&#xff0c;它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式…...

MyBatis的知识点和简单用法

MyBatis 是一个半ORM&#xff08;对象关系映射&#xff09;框架&#xff0c;它内部封装了JDBC&#xff0c;开发时只需要关注SQL语句本身&#xff0c;不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。程序员直接编写原生态sql&#xff0c;可以严格控制sql执…...

KITTI数据集(.bin数据)转换为点云数据(.pcd文件)

目录 cmake代码 代码 cmake代码 cmake_minimum_required(VERSION 3.17) project(TEST2)set(CMAKE_CXX_STANDARD 14)# Find PCL find_package(PCL 1.8 REQUIRED)# If PCL was found, add its include directories to the project if(PCL_FOUND)include_directories(${PCL_INC…...

【电路笔记】-节点电压分析和网状电流分析

节点电压分析和网状电流分析 文章目录 节点电压分析和网状电流分析1、节点电压分析1.1 概述1.2 示例 2、网格电流分析2.1 概述2.2 示例 3、总结 正如我们在上一篇介绍电路分析基本定律的文章中所看到的&#xff0c;基尔霍夫电路定律 (KCL) 是计算任何电路中未知电压和电流的强大…...

jenkins通知

构建失败邮件通知 配置自己的邮箱 配置邮件服务&#xff0c;密码是授权码 添加构建后操作 扩展 配置流水线 添加扩展 钉钉通知 Jenkins安装钉钉插件 钉钉添加机器人 加签 https://oapi.dingtalk.com/robot/send?access_token98437f84ffb6cd64fa2d7698ef44191d49a11…...

技术分享 | Spring Boot 异常处理

Java 异常类 首先让我们简单了解或重新学习下 Java 的异常机制。 Java 内部的异常类 Throwable 包括了 Exception 和 Error 两大类&#xff0c;所有的异常类都是 Object 对象。 Error 是不可捕捉的异常&#xff0c;通俗的说就是由于 Java 内部 JVM 引起的不可预见的异常&#…...

【Python 千题 —— 基础篇】成绩评级

题目描述 题目描述 期末考试结束&#xff0c;请根据同学的分数为该同学评级。 A&#xff1a;90 ~ 100B&#xff1a;80 ~ 89C&#xff1a;70 ~ 79D&#xff1a;60 ~ 69E&#xff1a;0 ~ 60 输入描述 输入同学的分数。 输出描述 输出该同学的等级。 示例 示例 ① 输入&…...

【ARM Coresight OpenOCD 系列 2 -- OpenOCD 脚本语法详细介绍】

请阅读【ARM Coresight SoC-400/SoC-600 专栏导读】 文章目录 1.1 swj-dp.tcl 介绍1.1.1 source [find target/swj-dp.tcl]1.1.2 调试传输协议选择 transport selec1.1.3 newtap 命令介绍1.1.4 内存读取数据函数 mem2array1.1.5 变量名检查1.1.6 设置 flash 烧录用到的 ram 空…...

别再死记硬背了!用“数据库查询”和“信号处理”的视角,5分钟彻底搞懂Transformer的Attention机制

从数据库查询到信号滤波&#xff1a;用跨界思维拆解Transformer注意力机制 在咖啡馆的玻璃窗前&#xff0c;一位工程师正用铅笔在餐巾纸上画着奇怪的符号——左边是数据库表结构&#xff0c;右边是滤波器电路图。这看似毫不相关的两件事&#xff0c;却意外地成为了理解Transfor…...

STM32 HardFault调试实战:用Keil的Call Stack快速定位崩溃代码

STM32 HardFault调试实战&#xff1a;用Keil的Call Stack快速定位崩溃代码 嵌入式开发中&#xff0c;HardFault异常就像一位不速之客&#xff0c;总是在最不合时宜的时刻出现。当你的STM32程序突然"跑飞"&#xff0c;最终停在HardFault_Handler的死循环中时&#xff…...

如何利用Stateflow与函数调用撕裂模块,在Simulink中构建多周期任务调度系统?

1. 多周期任务调度系统的核心挑战 在嵌入式系统开发中&#xff0c;资源受限的环境常常需要精细的任务调度策略。想象一下你正在设计一个智能家居控制器&#xff0c;需要同时处理以下任务&#xff1a;每10ms读取传感器数据&#xff08;高实时性&#xff09;、每100ms更新设备状态…...

告别网盘限速:2025年直链下载助手全面解析与实战指南

告别网盘限速&#xff1a;2025年直链下载助手全面解析与实战指南 【免费下载链接】Online-disk-direct-link-download-assistant 一个基于 JavaScript 的网盘文件下载地址获取工具。基于【网盘直链下载助手】修改 &#xff0c;支持 百度网盘 / 阿里云盘 / 中国移动云盘 / 天翼云…...

别再乱翻文件了!Windows应急响应高效排查术:快速定位Vulntarget中的恶意文件

Windows应急响应实战&#xff1a;三招精准定位Webshell的恶意文件 应急响应就像一场与时间赛跑的狩猎游戏。当服务器告警响起&#xff0c;面对成千上万的文件和日志条目&#xff0c;如何快速揪出攻击者留下的Webshell&#xff1f;传统方法往往让人陷入文件海洋中盲目翻找&#…...

Markdown Viewer:浏览器中的Markdown全能阅读器,让技术文档焕然一新

Markdown Viewer&#xff1a;浏览器中的Markdown全能阅读器&#xff0c;让技术文档焕然一新 【免费下载链接】markdown-viewer Markdown Viewer / Browser Extension 项目地址: https://gitcode.com/gh_mirrors/ma/markdown-viewer 你是否曾经在浏览器中打开一个Markdow…...

芯片设计中的Vt选择:如何平衡SVT、LVT和ULVT的速度与功耗

芯片设计中的Vt选择&#xff1a;如何平衡SVT、LVT和ULVT的速度与功耗 在28nm以下先进工艺节点中&#xff0c;阈值电压&#xff08;Vt&#xff09;选择已成为芯片设计的关键决策点。某次流片失败案例显示&#xff0c;由于ULVT单元使用比例过高&#xff0c;导致芯片静态功耗超标4…...

如何永久保存微信聊天记录?WeChatMsg终极解决方案指南

如何永久保存微信聊天记录&#xff1f;WeChatMsg终极解决方案指南 【免费下载链接】WeChatMsg 提取微信聊天记录&#xff0c;将其导出成HTML、Word、CSV文档永久保存&#xff0c;对聊天记录进行分析生成年度聊天报告 项目地址: https://gitcode.com/GitHub_Trending/we/WeCha…...

基于STM32L4XX的环境光传感器(TCS34727FN)应用程序设计

一、简介: TCS34727FN是一款集成了红外滤光片的数字颜色传感器,能输出RGB三原色和Clear(无滤光)四个通道的16位数据。 二、主要技术特性: 核心功能:颜色光数字转换器(红、绿、蓝、Clear) 关键特性:内置红外滤光片(抑制红外成分,提升色彩精度) 接口:IC(VBUS=1.…...

微信聊天记录导出终极指南:WeChatExporter让你轻松备份珍贵记忆

微信聊天记录导出终极指南&#xff1a;WeChatExporter让你轻松备份珍贵记忆 【免费下载链接】WeChatExporter 一个可以快速导出、查看你的微信聊天记录的工具 项目地址: https://gitcode.com/gh_mirrors/wec/WeChatExporter 你是否曾因手机丢失或更换而担心珍贵的微信聊…...