SpringFactoriesLoader![](https://img-blog.csdnimg.cn/direct/6add1990d81f42c68693fadc2dd7a3b0.png)
1.介绍
SpringFactoriesLoader类的主要作用是通过类路径下的META-INF/spring.factories文件获取工厂类接口的实现类,初始化并保存在缓存中,以供Springboot启动过程中各个阶段的调用。Spring的自动化配置功能,也与此息息相关。
SpringFactoriesLoader 工厂加载机制是 Spring 内部提供的一个约定俗成的加载方式,只需要在模块的 META-INF/spring.factories 文件中,以 Properties 类型(即 key-value 形式)配置,就可以将相应的实现类注入 Spirng 容器中。
Properties 类型格式:
key:value key:是全限定名(抽象类|接口)value:是实现类,多个实现类通过逗号进行分隔
Plain Text
spring boot 类路径下: META-INFO/spring.factories
# Logging Systemsorg.springframework.boot.logging.LoggingSystemFactory=\........
# Application Context Initializersorg.springframework.context.ApplicationContextInitializer=\......org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
# Application Listenersorg.springframework.context.ApplicationListener=\......org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
# Environment Post Processorsorg.springframework.boot.env.EnvironmentPostProcessor=\......org.springframework.boot.reactor.DebugAgentEnvironmentPostProcessor
# Failure Analyzersorg.springframework.boot.diagnostics.FailureAnalyzer=\......
Plain Text
2.方法
返回值 | 方法 | 描述 |
<T> List<T> | loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) | 静态方法; 根据接口获取其实现类的实例; 该方法返回的是实现类对象列表。 |
List<String> | loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) | 公共静态方法; 根据接口l获取其实现类的名称; 该方法返回的是实现类的类名的列表 |
public final class SpringFactoriesLoader {
//文件位置,可以存在多个JAR文件中
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
//用来缓存MultiValueMap对象
private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();
private SpringFactoriesLoader() {
}
/**
* 根据给定的类型加载并实例化工厂的实现类
*/
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);
if (logger.isTraceEnabled()) {
logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames);
}
//创建一个存放对象的List
List<T> result = new ArrayList<>(factoryImplementationNames.size());
for (String factoryImplementationName : factoryImplementationNames) {
//实例化Bean,并将Bean放入到List集合中
result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
}
//对List中的Bean进行排序
AnnotationAwareOrderComparator.sort(result);
return result;
}
/**
* 根据给定的类型加载类路径的全限定名
*/
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
//获取名称
String factoryTypeName = factoryType.getName();
//加载并获取所有META-INF/spring.factories中的value
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
//根据类加载器从缓存中获取,如果缓存中存在,就直接返回,如果不存在就去加载
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
//获取所有JAR及classpath路径下的META-INF/spring.factories的路径
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
//遍历所有的META-INF/spring.factories的路径
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
//将META-INF/spring.factories中的key value加载为Prpperties对象
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
//key名称
String factoryTypeName = ((String) entry.getKey()).trim();
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
//以factoryTypeName为key,value为值放入map集合中
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);
}
}
//实例化Bean对象
@SuppressWarnings("unchecked")
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);
}
}
}
Java
3.测试
首先在classpath:路径下新建一个META-INF/spring.factories文件,在里面配置如下:
com.beiyou.springboot04.service.StudentService=com.beiyou.springboot04.service.impl.StudentServiceImpl
Java
进行相关的测试
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//获取所有META-INF/spring.factories中的value值
List<String> factoryNames = SpringFactoriesLoader.loadFactoryNames(StudentService.class, ClassUtils.getDefaultClassLoader());
for (String name : factoryNames) {
System.out.println(name);
}
//实例化所有在META-INF/spring.factories配置的且实现BeanInfoFactory接口的类
List<StudentService> list = SpringFactoriesLoader.loadFactories(StudentService.class,DemoApplication.class.getClassLoader());
System.out.println(list.size());
}
}
Java
通过以上可以证明,SpringFactoriesLoader会寻找jar包中配置META-INF下的spring.factories配置文件相应Key的value,并根据需要实例化。
如何配置多个实现类?
com.beiyou.springboot04.service.StudentService=\
com.beiyou.springboot04.service.impl.StudentServiceImpl,\
com.beiyou.springboot04.service.impl.StudentServiceImpl2
运行结果如下: