spring.factories的常用配置项

news2024/9/21 16:50:01

概述       

       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> {
 
    @Override
    public 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> {
 
    @Override
    public 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 {
    @Override
    public 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 {

    @Override
    public 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()");
    }

    @Bean
    public Testbean testbean(){
        return new Testbean()
    }
    
    //注册过滤器
     @Bean
    public TestFilter testFilter(){
        return new TestFilter()
    }
 
}

FailureAnalyzer

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

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

/**
 * 自定义错误分析器
 */
public class TestFailureAnalyzer implements FailureAnalyzer {
 
    @Override
    public 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 {
 
    @Override
    public 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 {
        @PostConstruct
        public 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 {
    @Override
    public 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 {
    @Override
    public 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

得到以下日志;

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

qsort函数 结构体比较(strcmp函数(比较字符串的大小))

strcmp函数应用于qsort函数&#xff0c;排序创建函数指针时比较字符串大小。 这里我创建了一个简单的学生结构体&#xff0c;这个结构体只包含名字跟年龄两个信息。 在创建函数指针cmp_stu_age后&#xff0c;进行年龄大小比较&#xff0c;强制类型转换成stu*。 int cmp_stu_ag…

报错问题解决django.db.utils.OperationalError: (1049, “Unknown database ‘ mxshop‘“)

开发环境&#xff1a;ubuntu22.04 pycharm 功能&#xff1a;django连接使用mysql数据库&#xff0c;各项配置看似正常 报错&#xff1a; django.db.utils.OperationalError: (1049, "Unknown database mxshop") 分析检查原因&#xff1a; Setting的配置文件内&…

【JavaEE】_HttpServletResponse类

目录 1. 核心方法 2. 关于setStatus(400)与sendError 2.1 setStatus(400) 2.2 sendError 3. setHeader方法 4. 构造重定向响应 4.1 使用setHeader和setStatus实现重定向 4.2 使用sendRedirect实现重定向 本专栏已有文章介绍HttpServlet和HttpServletRequest类&#…

使用Python语言实现一个基于动态数组的序列队列

一、动态数组的实现 首先&#xff0c;我们需要创建一个DynamicArray类&#xff0c;该类将管理我们的动态数组。 动态数组能够动态地调整其大小&#xff0c;以容纳更多的元素。 目录 一、动态数组的实现 代码示例&#xff1a; 二、序列队列的实现 接下来&#xff0c;我…

【rust】10 project、crate、mod、pub、use、项目目录层级组织、概念和实战

文章目录 一、项目目录层级组织概念1.1 cargo new 创建同名 的 Project 和 crate1.2 多 crate 的 package1.3 mod 模块1.3.1 创建嵌套 mod1.3.2 mod 树1.3.3 用路径引用 mod1.3.3.1 使用绝对还是相对? 1.3.4 代码可见性1.3.4.1 pub 关键字1.3.4.2 用 super 引用 mod1.3.4.3 用…

Mathtype安装时word启动显示“文件未找到:MathPage.WLL”

背景 由于老板布置的临时工作&#xff0c;需要安装Mathtype&#xff0c;但尝试了3个不同的版本后&#xff08;每次都卸载干净了&#xff09;&#xff0c;均未能成功安装&#xff0c;出现的报错3个版本各不相同&#xff1a; ①解压安装过程中失败&#xff08;这个版本不再尝试…

数据可视化原理-腾讯-热力图

在做数据分析类的产品功能设计时&#xff0c;经常用到可视化方式&#xff0c;挖掘数据价值&#xff0c;表达数据的内在规律与特征展示给客户。 可是作为一个产品经理&#xff0c;&#xff08;1&#xff09;如果不能够掌握各类可视化图形的含义&#xff0c;就不知道哪类数据该用…

MySQL、高级SQL操作

学习数据库的目的 岗位需求、大数据时代、被迫需求&#xff0c;存数据 数据库是所有软件体系中最核心的存在 数据库 DB DB dataBase 数据仓库&#xff0c;软件&#xff0c;安装在window、linux、mac上&#xff0c;可以存储大量数据&#xff0c;500w 作用&#xff1a;存储数据…

docker的数据卷和docker的自定义镜像

docker的数据卷和docker的自定义镜像 1.docker的数据卷1.1创建 docker volume create 数据卷名称1.2 查看数据卷docker volume ls1.3 删除一个volume 2.将宿主机的目录与容器的目录进行挂载&#xff0c;实现数据共享2.1数据卷相互共享 3.自定义镜像3.1编辑Dockerfiile文件 vim …

位运算第二弹

力扣191.位1的个数 public class Solution {// you need to treat n as an unsigned valuepublic int hammingWeight(int n) {int ret0;while(n!0){n(n&n-1);ret;}return ret;} } 推荐是自己去手动推一下&#xff0c;深刻理解一下&#xff0c;什么叫做最右侧的1。 力扣338.…

3694-51-7,3,5-Dinitro-1,2-phenylenediamine,合成其他化合物的重要中间体

您好&#xff0c;欢迎来到新研之家 文章关键词&#xff1a;3694-51-7&#xff0c;3,5-Dinitro-1,2-phenylenediamine&#xff0c;3,5-二硝基-1,2-苯二胺;3,5-二硝基苯-1,2-二胺 一、基本信息 【产品简介】&#xff1a;3,5-Dinitro-1,2-phenylenediamine, with the molecular…

MySql出现无法正常启动(0x000007b)的快速解决

目录 1.背景介绍 2.解决方案 1.背景介绍 昨天在清理电脑内存空间的时候&#xff0c;不小心将一些重要的系统组件删除&#xff0c;导致无法正常启动mysql&#xff0c;一开始是提示经过msvcp120.dll&#xff0c;于是找到下载dll的网站将组件补充进system&#xff0c;但随后又提…

【办公类-25-01】20240304 UIBOT上传 ”班级主页-信息窗“

一、背景需求&#xff1a; 本学期制作了 “信息窗主题说明”合并A4内容 【办公类-22-07】周计划系列&#xff08;3-1&#xff09;“信息窗主题知识&#xff08;提取&#xff09;” &#xff08;2024年调整版本&#xff09;-CSDN博客文章浏览阅读797次&#xff0c;点赞7次&…

渗压计使用中的常见问题及其解决方案

渗压计作为一种用于测量土壤或岩石中孔隙水压力的重要工具&#xff0c;在地质工程和水文学领域具有广泛的应用。然而&#xff0c;在实际使用过程中&#xff0c;渗压计可能会遇到多种常见问题&#xff0c;这些问题不仅影响测量精度&#xff0c;还可能对设备本身造成损害。本文将…

【力扣】207.课程表(图)

依旧还是有关于图的题目&#xff0c;这次不一样的点在于题目并没有明确的给出他是图的题目的形式&#xff0c;而是说让你根据其题目意思来进行操作。 首先&#xff0c;就是搞清楚题目的意思。假设你想学习A课程&#xff0c;那就是必须先学习B课程&#xff0c;但是这里给出的例…

消息队列+更新DB极易引发的DB并发修改bug

背景 我们在生产系统中和其他系统进行交互时一般都会通过消息队列来解耦生产者和消费者&#xff0c;然后通过每个使用方消费消息队列的消息的方式来完成消息的消费&#xff0c;并且一般来说我们消费消息后极有可能会操作DB&#xff0c;不过这种方式如果处理不够仔细&#xff0…

Linux——进程控制(一)进程的创建与退出

目录 一、进程创建 1.写时拷贝 2.创建多个进程 二、进程终止 1.main函数的返回值 2.bash中的$? 3.自定义退出码 4.C语言的错误码 5.错误码与退出码的区别 6.代码异常终止 7.exit函数 8.总结 一、进程创建 在之前&#xff0c;我们学过linux中的非常重要的函数——…

全网爆火的 MBTI 测试,是隐藏的割韭菜工具?

小伙伴们&#xff0c;谁能想到&#xff0c;作为一名冲浪老手&#xff0c;果子在网上又被骗了。 事情是这样的&#xff0c;前几天&#xff0c;我刷微博&#xff0c;看到一个推荐&#xff0c;大概如下图&#xff0c;是一个 MBTI 人格测试。 MBTI 测试&#xff0c;果子早就做过了…

【前端素材】推荐优质在线电影院商城电商网页Hyper平台模板(附源码)

一、需求分析 1、系统定义 在线电影商城是指一个通过互联网提供电影服务的平台&#xff0c;用户可以在该平台上浏览电影资源、租借或购买电影&#xff0c;以及观看在线影片。 2、功能需求 在线电影商城是指一个通过互联网提供电影服务的平台&#xff0c;用户可以在该平台上…

Windows Docker 部署 Redis

部署 Redis 打开 Docker Desktop&#xff0c;切换到 Linux 内核。然后在 PowerShell 执行下面命令&#xff0c;即可启动一个 redis 服务。这里安装的是 7.2.4 版本&#xff0c;如果需要安装其他或者最新版本&#xff0c;可以到 Docker Hub 中进行查找。 docker run -d --nam…