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

spring.factories的常用配置项

概述       

       spring.factories 实现是依赖 spring-core 包里的 SpringFactoriesLoader 类,这个类实现了检索 META-INF/spring.factories 文件,并获取指定接口的配置的功能。

        Spring Factories机制提供了一种解耦容器注入的方式,帮助外部包(独立于spring-boot项目)注册Bean到spring boot项目容器中。spring.factories 这种机制实际上是仿照 java 中的 SPI 扩展机制实现的。

Spring Factories机制原理

核心类SpringFactoriesLoader

       从上文可知,Spring Factories机制通过META-INF/spring.factories文件获取相关的实现类的配置信息,而SpringFactoriesLoader的功能就是读取META-INF/spring.factories,并加载配置中的类。SpringFactoriesLoader主要有两个方法:loadFactories和loadFactoryNames。

loadFactoryNames

用于按接口获取Spring Factories文件中的实现类的全称,其方法定义如下所示,其中参数factoryType指定了需要获取哪个接口的实现类,classLoader用于读取配置文件资源。 public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader)

loadFactories

用于按接口获取Spring Factories文件中的实现类的实例,其方法定义如下所示,其中参数factoryType指定了需要获取哪个接口的实现类,classLoader用于读取配置文件资源和加载类。 public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader)

用法及配置

        spring.factories 文件必须放在 resources 目录下的 META-INF 的目录下,否则不会生效。如果一个接口希望配置多个实现类,可以用","分割。

BootstrapConfiguration

        该配置项用于自动引入配置源,类似于spring-cloud的bootstrap和nacos的配置,通过指定的方式加载我们自定义的配置项信息。该配置项配置的类必须是实现了PropertySourceLocator接口的类。

org.springframework.cloud.bootstrap.BootstrapConfiguration=\ xxxxxx.configure.config.ApplicationConfigure

public class ApplicationConfigure {@Bean@ConditionalOnMissingBean({CoreConfigPropertySourceLocator.class})public CoreConfigPropertySourceLocator configLocalPropertySourceLocator() {return new CoreConfigPropertySourceLocator();}
}public class CoreConfigPropertySourceLocator implements PropertySourceLocator {
.....
}

ApplicationContextInitializer

该配置项用来配置实现了 ApplicationContextInitializer 接口的类,这些类用来实现上下文初始化

 org.springframework.context.ApplicationContextInitializer=\
xxxxxx.config.TestApplicationContextInitializer

public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {@Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {System.out.println("TestApplicationContextInitializer.initialize() " + applicationContext);}}

 ApplicationListener

        配置应用程序监听器,该监听器必须实现 ApplicationListener 接口。它可以用来监听 ApplicationEvent 事件。

org.springframework.context.ApplicationListener=\
xxxxxxx.factories.listener.TestApplicationListener

@Slf4j
public class TestApplicationListener implements ApplicationListener<TestMessageEvent> {@Overridepublic void onApplicationEvent(EmailMessageEvent event) {log.info("模拟消息事件... ");log.info("TestApplicationListener 接受到的消息:{}", event.getContent());}
}

AutoConfigurationImportListener

        该配置项用来配置自动配置导入监听器,监听器必须实现 AutoConfigurationImportListener  接口。该监听器可以监听 AutoConfigurationImportEvent 事件。

org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
xxxx.config.TestAutoConfigurationImportListener

public class TestAutoConfigurationImportListener implements AutoConfigurationImportListener {@Overridepublic void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {System.out.println("TestAutoConfigurationImportListener.onAutoConfigurationImportEvent() " + event);}
}

AutoConfigurationImportFilter

        配置自动配置导入过滤器,过滤器必须实现 AutoConfigurationImportFilter 接口。该过滤器用来过滤那些自动配置类可用。

org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
xxxxxx.config.TestConfigurationCondition

public class TestConfigurationCondition implements AutoConfigurationImportFilter {@Overridepublic boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {System.out.println("TestConfigurationCondition.match() autoConfigurationClasses=" +  Arrays.toString(autoConfigurationClasses) + ", autoConfigurationMetadata=" + autoConfigurationMetadata);return new boolean[0];}
}

EnableAutoConfiguration

      配置自动配置类。这些配置类需要添加 @Configuration 注解,可用于注册bean。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
xxxxx.config.TestConfiguration

@Configuration
public class MyConfiguration {public MyConfiguration() {System.out.println("MyConfiguration()");}@Beanpublic Testbean testbean(){return new Testbean()}//注册过滤器@Beanpublic TestFilter testFilter(){return new TestFilter()}}

FailureAnalyzer

         配置自定的错误分析类,该分析器需要实现 FailureAnalyzer 接口。

org.springframework.boot.diagnostics.FailureAnalyzer=\
xxxxx.config.TestFailureAnalyzer

/*** 自定义错误分析器*/
public class TestFailureAnalyzer implements FailureAnalyzer {@Overridepublic FailureAnalysis analyze(Throwable failure) {System.out.println("TestFailureAnalyzer.analyze() failure=" + failure);return new FailureAnalysis("TestFailureAnalyzer execute", "test spring.factories", failure);}}

TemplateAvailabilityProvider

        配置模板的可用性提供者,提供者需要实现 TemplateAvailabilityProvider 接口。

org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
xxxxx.config.TestTemplateAvailabilityProvider

/*** 验证指定的模板是否支持*/
public class TestTemplateAvailabilityProvider implements TemplateAvailabilityProvider {@Overridepublic boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) {System.out.println("TestTemplateAvailabilityProvider.isTemplateAvailable() view=" + view + ", environment=" + environment + ", classLoader=" + classLoader + "resourceLoader=" + resourceLoader);return false;}}

自定义Spring Factories机制

        首先我们需要先定义两个模块,第一个模块A用于定义interface和获取interface的实现类。

代码如下:

package com.zhong.spring.demo.demo_7_springfactories;public interface DemoService {void printName();
}package com.zhong.spring.demo.demo_7_springfactories;import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;
import java.util.List;@Slf4j
@Service
public class DemoServiceFactory {@PostConstructpublic void printService(){List<String> serviceNames = SpringFactoriesLoader.loadFactoryNames(DemoService.class,null);for (String serviceName:serviceNames){log.info("name:" + serviceName);}List<DemoService> services = SpringFactoriesLoader.loadFactories(DemoService.class,null);for (DemoService demoService:services){demoService.printName();}}
}

另一个模块B引入A模块,并实现DemoService类。并且配置spring.factories

代码如下:

package com.zhong.spring.usuldemo.impl;import com.zhong.spring.demo.demo_7_springfactories.DemoService;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class DemoServiceImpl1 implements DemoService {@Overridepublic void printName() {log.info("-----------DemoServiceImpl2------------");}
}import com.zhong.spring.demo.demo_7_springfactories.DemoService;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class DemoServiceImpl2 implements DemoService {@Overridepublic void printName() {log.info("-----------DemoServiceImpl2------------");}
}

 spring.factory配置如下:

com.zhong.spring.demo.demo_7_springfactories.DemoService=\
    com.zhong.spring.usuldemo.impl.DemoServiceImpl1,\
    com.zhong.spring.usuldemo.impl.DemoServiceImpl2

启动模块B

得到以下日志;

相关文章:

spring.factories的常用配置项

概述 spring.factories 实现是依赖 spring-core 包里的 SpringFactoriesLoader 类&#xff0c;这个类实现了检索 META-INF/spring.factories 文件&#xff0c;并获取指定接口的配置的功能。 Spring Factories机制提供了一种解耦容器注入的方式&#xff0c;帮助外部包&am…...

数据库-第二/三章 关系数据库和标准语言SQL【期末复习|考研复习】

前言 总结整理不易&#xff0c;希望大家点赞收藏。 给大家整理了一下计数据库系统概论中的重点概念&#xff0c;以供大家期末复习和考研复习的时候使用。 参考资料是王珊老师和萨师煊老师的数据库系统概论(第五版)。 文章目录 前言第二、三章 关系数据库和标准语言SQL2.1 关系2…...

【办公类-21-05】20240227单个word按“段落数”拆分多个Word(成果汇编 只有段落文字 1拆5)

作品展示 背景需求 前文对一套带有段落文字和表格的word进行13份拆分 【办公类-21-04】20240227单个word按“段落数”拆分多个Word&#xff08;三级育婴师操作参考题目1拆13份&#xff09;-CSDN博客文章浏览阅读293次&#xff0c;点赞8次&#xff0c;收藏3次。【办公类-21-04…...

【前端素材】推荐优质后台管理系统网页my-Task平台模板(附源码)

一、需求分析 1、系统定义 后台管理系统是一种用于管理网站、应用程序或系统的工具&#xff0c;通常由管理员使用。后台管理系统是一种用于管理和控制网站、应用程序或系统的管理界面。它通常被设计用来让网站或应用程序的管理员或运营人员管理内容、用户、数据以及其他相关功…...

Linux高负载排查最佳实践

在Linux系统中&#xff0c;经常会因为负载过高导致各种性能问题。那么如何进行排查&#xff0c;其实是有迹可循&#xff0c;而且模式固定。 本次就来分享一下&#xff0c;CPU占用过高、磁盘IO占用过高的排查方法。 还是那句话&#xff0c;以最佳实践入手&#xff0c;真传一句话…...

【python开发】网络编程(上)

这里写目录标题 一、必备基础&#xff08;一&#xff09;网络架构1、交换机2、路由器3、三层交换机4、小型企业基础网络架构5、家庭网络架构6、互联网 &#xff08;二&#xff09;网络核心词汇1、子网掩码和IP2、DHCP3、内网和公网IP4、云服务器5、端口6、域名 一、必备基础 &…...

php源码 单色bmp图片取模工具 按任意方式取模 生成字节数组 自由编辑点阵

http://2.wjsou.com/BMP/index.html 想试试chatGPT4生成&#xff0c;还是要手工改 php 写一个网页界面上可以选择一张bmp图片&#xff0c;界面上就显示这张bmp图片&#xff0c; 点生成取模按钮&#xff0c;在图片下方会显示这张bmp图片的取模数据。 取模规则是按界面设置的&a…...

设计模式-命令模式(Command Pattern)

承接Qt/C软件开发项目&#xff0c;高质量交付&#xff0c;灵活沟通&#xff0c;长期维护支持。需求所寻&#xff0c;技术正适&#xff0c;共创完美&#xff0c;欢迎私信联系&#xff01; 一、命令模式的说明 命令模式&#xff08;Command Pattern&#xff09;是一种行为设计模式…...

鸿蒙Harmony应用开发—ArkTS声明式开发(通用属性:位置设置)

设置组件的对齐方式、布局方向和显示位置。 说明&#xff1a; 从API Version 7开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 align align(value: Alignment) 设置容器元素绘制区域内的子元素的对齐方式。 卡片能力&#xff1a; 从API…...

ShardingJdbc实战-分库分表

文章目录 基本配置分库分表的分片策略一、inline 行表达时分片策略algorithm-expression行表达式完整案例和配置如下 二、根据实时间日期 - 按照标准规则分库分表标准分片 - Standard完整案例和配置如下 基本配置 逻辑表 逻辑表是指&#xff1a;水平拆分的数据库或者数据表的相…...

51单片机-(定时/计数器)

51单片机-&#xff08;定时/计数器&#xff09; 了解CPU时序、特殊功能寄存器和定时/计数器工作原理&#xff0c;以定时器0实现每次间隔一秒亮灯一秒的实验为例理解定时/计数器的编程实现。 1.CPU时序 1.1.四个周期 振荡周期&#xff1a;为单片机提供定时信号的振荡源的周期…...

midjourney提示词语法

更高级的提示可以包括一个或多个图像URL、多个文本短语和一个或更多个参数 Image Prompts 可以将图像URL添加到提示中&#xff0c;以影响最终结果的样式和内容。图像URL总是位于提示的前面。 https://docs.midjourney.com/image-prompts Text Prompt 要生成的图像的文本描述。…...

【鸿蒙 HarmonyOS 4.0】路由router

一、介绍 页面路由指在应用程序中实现不同页面之间的跳转和数据传递。HarmonyOS提供了Router模块&#xff0c;通过不同的url地址&#xff0c;可以方便地进行页面路由&#xff0c;轻松地访问不同的页面。 二、页面跳转 2.1、两种跳转模式&#xff1a; router.pushUrl()&…...

AT24C1024的模拟IIC驱动

AT24C1024是基于IIC的EEPROM&#xff0c;容量为1024/8128k bytes。它的引脚如下&#xff1a; 其中A1,A2为硬件地址引脚 WP为写保护引脚&#xff0c;一般我们需要读写&#xff0c;需要接低电平GND&#xff0c;接高的话则仅允许读 SDA和SCL则为IIC通信引脚 芯片通信采用IIC&…...

Stable Diffusion生成式扩散模型代码实现原理

Stable Diffusion可以使用PyTorch或TensorFlow等深度学习框架来实现。这些框架提供了一系列的工具和函数&#xff0c;使得开发者可以更方便地构建、训练和部署深度学习模型。因此可以使用PyTorch或TensorFlow来实现Stable Diffusion模型。 安装PyTorch&#xff1a;确保您已经安…...

解决Keepalived “脑裂”(双VIP)问题

1. 检查广播情况 yum install tcpdump -y tcpdump -i ens33 vrrp -n master 192.168.80.130 与 backup: 192.168.80.131都在广播&#xff0c;正常情况下backup应该是不在广播的&#xff0c;所以可以判断存在防火墙屏蔽vrrp问题&#xff0c;需要设置VRRP过掉防火墙&#xff0…...

cAdvisor+Prometheus+Grafana 搞定Docker容器监控平台

cAdvisorPrometheusGrafana cAdvisorPrometheusGrafana 搞定Docker容器监控平台1、先给虚拟机上传cadvisor2、What is Prometheus?2.1、架构图 3、利用docker安装普罗米修斯4、安装grafana cAdvisorPrometheusGrafana 搞定Docker容器监控平台 1、先给虚拟机上传cadvisor cAd…...

java基础知识面试题

下面是关于java基础知识的一些常见面试题 equals 与区别 在Java中&#xff0c;""是一个比较操作符&#xff0c;用于比较两个变量的值是否相等。而"equals()"是Object类中定义的方法&#xff0c;用于比较两个对象是否相等。 具体区别如下&#xff1a; &…...

科技云报道:黑马Groq单挑英伟达,AI芯片要变天?

科技云报道原创。 近一周来&#xff0c;大模型领域重磅产品接连推出&#xff1a;OpenAI发布“文字生视频”大模型Sora&#xff1b;Meta发布视频预测大模型 V-JEPA&#xff1b;谷歌发布大模型 Gemini 1.5 Pro&#xff0c;更毫无预兆地发布了开源模型Gemma… 难怪网友们感叹&am…...

解决i18n国际化可读性问题,傻瓜式webpack中文支持国际化插件开发

先来看最后的效果 问题 用过国际化i18n的朋友都知道&#xff0c;天下苦国际化久矣&#xff0c;尤其是中文为母语的开发者&#xff0c;在面对代码中一堆的$t(abc.def)这种一点也不直观毫无可读性的代码&#xff0c;根本不知道自己写了啥 &#xff08;如上图&#xff0c;你看得出…...

多云管理“拦路虎”:深入解析网络互联、身份同步与成本可视化的技术复杂度​

一、引言&#xff1a;多云环境的技术复杂性本质​​ 企业采用多云策略已从技术选型升维至生存刚需。当业务系统分散部署在多个云平台时&#xff0c;​​基础设施的技术债呈现指数级积累​​。网络连接、身份认证、成本管理这三大核心挑战相互嵌套&#xff1a;跨云网络构建数据…...

vscode(仍待补充)

写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh&#xff1f; debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

【Web 进阶篇】优雅的接口设计:统一响应、全局异常处理与参数校验

系列回顾&#xff1a; 在上一篇中&#xff0c;我们成功地为应用集成了数据库&#xff0c;并使用 Spring Data JPA 实现了基本的 CRUD API。我们的应用现在能“记忆”数据了&#xff01;但是&#xff0c;如果你仔细审视那些 API&#xff0c;会发现它们还很“粗糙”&#xff1a;有…...

unix/linux,sudo,其发展历程详细时间线、由来、历史背景

sudo 的诞生和演化,本身就是一部 Unix/Linux 系统管理哲学变迁的微缩史。来,让我们拨开时间的迷雾,一同探寻 sudo 那波澜壮阔(也颇为实用主义)的发展历程。 历史背景:su的时代与困境 ( 20 世纪 70 年代 - 80 年代初) 在 sudo 出现之前,Unix 系统管理员和需要特权操作的…...

uniapp中使用aixos 报错

问题&#xff1a; 在uniapp中使用aixos&#xff0c;运行后报如下错误&#xff1a; AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...

华为云Flexus+DeepSeek征文|DeepSeek-V3/R1 商用服务开通全流程与本地部署搭建

华为云FlexusDeepSeek征文&#xff5c;DeepSeek-V3/R1 商用服务开通全流程与本地部署搭建 前言 如今大模型其性能出色&#xff0c;华为云 ModelArts Studio_MaaS大模型即服务平台华为云内置了大模型&#xff0c;能助力我们轻松驾驭 DeepSeek-V3/R1&#xff0c;本文中将分享如何…...

JVM暂停(Stop-The-World,STW)的原因分类及对应排查方案

JVM暂停(Stop-The-World,STW)的完整原因分类及对应排查方案,结合JVM运行机制和常见故障场景整理而成: 一、GC相关暂停​​ 1. ​​安全点(Safepoint)阻塞​​ ​​现象​​:JVM暂停但无GC日志,日志显示No GCs detected。​​原因​​:JVM等待所有线程进入安全点(如…...

在Ubuntu24上采用Wine打开SourceInsight

1. 安装wine sudo apt install wine 2. 安装32位库支持,SourceInsight是32位程序 sudo dpkg --add-architecture i386 sudo apt update sudo apt install wine32:i386 3. 验证安装 wine --version 4. 安装必要的字体和库(解决显示问题) sudo apt install fonts-wqy…...

保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek

文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama&#xff08;有网络的电脑&#xff09;2.2.3 安装Ollama&#xff08;无网络的电脑&#xff09;2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...

LangChain知识库管理后端接口:数据库操作详解—— 构建本地知识库系统的基础《二》

这段 Python 代码是一个完整的 知识库数据库操作模块&#xff0c;用于对本地知识库系统中的知识库进行增删改查&#xff08;CRUD&#xff09;操作。它基于 SQLAlchemy ORM 框架 和一个自定义的装饰器 with_session 实现数据库会话管理。 &#x1f4d8; 一、整体功能概述 该模块…...