SpringFactoriesLoader解析
一、SpringFactoriesLoader 介绍
1.1 SpringFactoriesLoader 简介
SpringFactoriesLoader 工厂加载机制是 Spring 内部提供的一个约定俗成的加载方式,与 java spi 类似,只需要在模块的 META-INF/spring.factories 文件中,以 Properties 类型(即 key-value 形式)配置,就可以将相应的实现类注入 Spirng 容器中。
Properties 类型格式:
key:是全限定名(抽象类|接口)
value:是实现,多个实现通过 **逗号** 进行分隔
1.2 SpringFactoriesLoader 常用方法
loadFactoryNames
读取 classpath上 所有的 jar 包中的所有 META-INF/spring.factories属 性文件,找出其中定义的匹配类型 factoryClass 的工厂类,然后并返回这些工厂类的名字列表,注意是包含包名的全限定名。
loadFactories
读取 classpath 上所有的jar包中的所有 META-INF/spring.factories 属性文件,找出其中定义的匹配类型 factoryClass 的工厂类,然后创建每个工厂类的对象/实例,并返回这些工厂类对象/实例的列表。
1.3 loadFactories 流程图

二、SpringFactoriesLoader 源码解析
2.1 loadFactoryNames 解析
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
// 获取包含包名的工厂类名称
String factoryTypeName = factoryType.getName();
// 获取所有配置在 META-INF/spring.factories 文件的值
// 然后获取指定类的实现类名列表
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
// 默认的工厂配置路径地址,可以存放在多个 JAR 包下
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
// 判断是否有缓存结果,如果有直接返回
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
// 扫描 classpath 上所有 JAR 中的文件 META-INF/spring.factories
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
// 找到的每个 META-INF/spring.factories 文件都是一个 Properties 文件,将其内容加载到一个 Properties 对象然后处理其中的每个属性
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
// 获取工厂类名称(接口或者抽象类的全限定名)
String factoryTypeName = ((String) entry.getKey()).trim();
// 将逗号分割的属性值逐个取出,然后放到 结果result 中去
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
// 将结果存放到缓存中
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
2.2 loadFactories 解析
public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {
Assert.notNull(factoryType, "'factoryType' must not be null");
// 如果未指定类加载器,则使用默认的
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
// 获取指定工厂名称列表
List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
// 如果记录器Trace跟踪激活的话,将工厂名称列表输出
if (logger.isTraceEnabled()) {
logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames);
}
// 创建结果集
List<T> result = new ArrayList<>(factoryImplementationNames.size());
for (String factoryImplementationName : factoryImplementationNames) {
// 实例化工厂类,并添加到结果集中
result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
}
// 对结果集列表进行排序
AnnotationAwareOrderComparator.sort(result);
return result;
}
private static <T> T instantiateFactory(String factoryImplementationName, Class<T> factoryType, ClassLoader classLoader) {
try {
Class<?> factoryImplementationClass = ClassUtils.forName(factoryImplementationName, classLoader);
if (!factoryType.isAssignableFrom(factoryImplementationClass)) {
throw new IllegalArgumentException(
"Class [" + factoryImplementationName + "] is not assignable to factory type [" + factoryType.getName() + "]");
}
return (T) ReflectionUtils.accessibleConstructor(factoryImplementationClass).newInstance();
}
catch (Throwable ex) {
throw new IllegalArgumentException(
"Unable to instantiate factory class [" + factoryImplementationName + "] for factory type [" + factoryType.getName() + "]",
ex);
}
}
SpringFactoriesLoader解析的更多相关文章
- springboot源码解析 - 构建SpringApplication
1 package com.microservice.framework; 2 3 import org.springframework.boot.SpringApplication; 4 impor ...
- SpringBoot启动流程解析
写在前面: 由于该系统是底层系统,以微服务形式对外暴露dubbo服务,所以本流程中SpringBoot不基于jetty或者tomcat等容器启动方式发布服务,而是以执行程序方式启动来发布(参考下图ke ...
- springboot之启动原理解析
前言 SpringBoot为我们做的自动配置,确实方便快捷,但是对于新手来说,如果不大懂SpringBoot内部启动原理,以后难免会吃亏.所以这次博主就跟你们一起一步步揭开SpringBoot的神秘面 ...
- Spring Boot自动配置源码解析(基于Spring Boot 2.0.2.RELEASE)
在Spring Boot官方介绍中,首一段话是这样的(如下图).我们可以大概了解到其所表达的含义:我们可以利用Spring Boot写很少的配置来创建一个非常方便的基于Spring整合第三方类库的单体 ...
- spring boot(二):启动原理解析
我们开发任何一个Spring Boot项目,都会用到如下的启动类 @SpringBootApplication public class Application { public static voi ...
- SpringBoot的自动配置原理过程解析
SpringBoot的最大好处就是实现了大部分的自动配置,使得开发者可以更多的关注于业务开发,避免繁琐的业务开发,但是SpringBoot如此好用的 自动注解过程着实让人忍不住的去了解一番,因为本文的 ...
- SpringBoot初体验及原理解析
一.前言 上篇文章,我们聊到了SpringBoot得以实现的幕后推手,这次我们来用SpringBoot开始HelloWorld之旅.SpringBoot是Spring框架对“约定大于配置(Conv ...
- springboot之启动原理解析及源码阅读
前言 SpringBoot为我们做的自动配置,确实方便快捷,但是对于新手来说,如果不大懂SpringBoot内部启动原理,以后难免会吃亏.所以这次博主就跟你们一起一步步揭开SpringBoot的神秘面 ...
- 【转】Spring Boot干货系列:(三)启动原理解析
前言 前面几章我们见识了SpringBoot为我们做的自动配置,确实方便快捷,但是对于新手来说,如果不大懂SpringBoot内部启动原理,以后难免会吃亏.所以这次博主就跟你们一起一步步揭开Sprin ...
随机推荐
- Swiper中文网
http://3.swiper.com.cn/api/Slides_grid/2014/1215/24.html slidesPerView :2, 即设置slider容器能够同时显示的slide ...
- mac osx 下 浏览器 开启 java
工作环境mac osx 浏览器 chrome:63.0.3239.132 (Official Build) (64-bit)firefox: 57.0.4 (64 位)safari:Version 1 ...
- PXE自动部署工具
1.工具介绍1.1::本工具主要以图形界面的方式帮助使用者快速部署PXE安装Linux的基础环境环境,(如不需要可忽略相关操作)并且支持自动配置静态IP地址和为H3C设备划分VLAN. 1.2::对于 ...
- Java IO: FileReader和FileWriter
作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 本章节将简要介绍FileReader和FileWriter.与FileInputStream和File ...
- 查看pip安装的包的位置
- git 第一次上传本地代码到远程仓库,解决 ! [rejected] master -> master (non-fast-forward)错误
使用git想GitHub远程仓库上传代码的基本步骤一般是 初始化为git仓库 git init 添加所有要提交的文件 git add . 本次提交说明 git commit -m '提交说明' 关联G ...
- 关于JavaScript中bind、applay、call的区别
在JavaScript中this的指向一直是一个困扰我们的问题,在JavaScript中this的指向是不固定的,但是我们可以通过使用bind().call().apply()来改变this的指向,但 ...
- spring boot 创建定时任务
@Scheduled默认创建的线程是单线程,任务的执行会受到上一个任务的影响,创建定时任务也比较简单 123456789101112 @Component@Configuration //1.主要用于 ...
- 吴裕雄--天生自然 PYTHON语言数据分析:ESA的火星快车操作数据集分析
import os import numpy as np import pandas as pd from datetime import datetime import matplotlib imp ...
- 使用Google App Engine开始新的网站开发学习
继长时间的迷茫后,我发现还是回归php网站开发更适合我,或者没有那么深刻,但至少要做点事情.不知道以后将从事什么样的工作,但现在找点事情做还是很好的.所以,为了激发我学习的热情,我在网上搜了一下免费云 ...