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 解析
?1234567public static List loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) { // 获取包含包名的工厂类名称 String factoryTypeName = factoryType.getName(); // 获取所有配置在 META-INF/spring.factories 文件的值 // 然后获取指定类的实现类名列表 return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());}public static List loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
// 获取包含包名的工厂类名称
String factoryTypeName = factoryType.getName();
// 获取所有配置在 META-INF/spring.factories 文件的值
// 然后获取指定类的实现类名列表
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}?123456789101112131415161718192021222324252627282930313233343536373839// 默认的工厂配置路径地址,可以存放在多个 JAR 包下public static final String FACTORIES_RESOURCE_LOCATION = “META-INF/spring.factories”; private static Map<String, List> loadSpringFactories(@Nullable ClassLoader classLoader) { // 判断是否有缓存结果,如果有直接返回 MultiValueMap<String, String> result = cache.get(classLoader); if (result != null) { return result; } try { // 扫描 classpath 上所有 JAR 中的文件 META-INF/spring.factories Enumeration 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); }}// 默认的工厂配置路径地址,可以存放在多个 JAR 包下
public static final String FACTORIES_RESOURCE_LOCATION = “META-INF/spring.factories”;

private static Map<String, List> loadSpringFactories(@Nullable ClassLoader classLoader) {
// 判断是否有缓存结果,如果有直接返回
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}

try {
// 扫描 classpath 上所有 JAR 中的文件 META-INF/spring.factories
Enumeration 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);
}
}?123456default V getOrDefault(Object key, V defaultValue) { V v; return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue;}default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}2.2 loadFactories 解析?1234567891011121314151617181920212223public static List loadFactories(Class factoryType, @Nullable ClassLoader classLoader) { Assert.notNull(factoryType, “‘factoryType’ must not be null”); // 如果未指定类加载器,则使用默认的 ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = SpringFactoriesLoader.class.getClassLoader(); } // 获取指定工厂名称列表 List factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse); // 如果记录器Trace跟踪激活的话,将工厂名称列表输出 if (logger.isTraceEnabled()) { logger.trace(“Loaded [” + factoryType.getName() + "] names: " + factoryImplementationNames); } // 创建结果集 List result = new ArrayList<>(factoryImplementationNames.size()); for (String factoryImplementationName : factoryImplementationNames) { // 实例化工厂类,并添加到结果集中 result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse)); } // 对结果集列表进行排序 AnnotationAwareOrderComparator.sort(result); return result;}public static List loadFactories(Class factoryType, @Nullable ClassLoader classLoader) {
Assert.notNull(factoryType, “‘factoryType’ must not be null”);
// 如果未指定类加载器,则使用默认的
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
// 获取指定工厂名称列表
List factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
// 如果记录器Trace跟踪激活的话,将工厂名称列表输出
if (logger.isTraceEnabled()) {
logger.trace(“Loaded [” + factoryType.getName() + "] names: " + factoryImplementationNames);
}
// 创建结果集
List result = new ArrayList<>(factoryImplementationNames.size());
for (String factoryImplementationName : factoryImplementationNames) {
// 实例化工厂类,并添加到结果集中
result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
}
// 对结果集列表进行排序
AnnotationAwareOrderComparator.sort(result);
return result;
}?123456789101112131415private static T instantiateFactory(String factoryImplementationName, Class 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); }}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值