spring.factories的常用配置项

2024-03-01 07:28

本文主要是介绍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的常用配置项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Redis Cluster模式配置

《RedisCluster模式配置》:本文主要介绍RedisCluster模式配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录分片 一、分片的本质与核心价值二、分片实现方案对比 ‌三、分片算法详解1. ‌范围分片(顺序分片)‌2. ‌哈希分片3. ‌虚

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477