Spring SpringFactoriesLoader


Spring SpringFactoriesLoader

Spring的SpringFactoriesLoader工廠的加載機制類似java提供的SPI機制一樣,是Spring提供的一種加載方式。只需要在classpath路徑下新建一個文件META-INF/spring.factories,並在里面按照Properties格式填寫好借口和實現類即可通過SpringFactoriesLoader來實例化相應的Bean。其中key可以是接口、注解、或者抽象類的全名。value為相應的實現類,當存在多個實現類時,用“,”進行分割。

SpringFactoriesLoader的主要屬性及方法

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);
		}
	}

}

下面來進行測試

首先在classpath:路徑下新建一個META-INF/spring.factories文件,在里面配置如下:

#com.rookie.bigdata.service.HelloService=com.rookie.bigdata.service.impl.HelloServiceImpl
org.springframework.beans.BeanInfoFactory=com.rookie.bigdata.service.impl.HelloServiceImpl

新建一個HelloServiceImpl類,並實現BeanInfoFactory接口

public class HelloServiceImpl implements BeanInfoFactory {

    public HelloServiceImpl(){
        System.out.println("實例化 HelloServiceImpl");
    }

    @Override
    public BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException {
        return null;
    }
}

進行相關的測試

@Test
public void testLoadFactoryNames() {
    //獲取所有META-INF/spring.factories中的value值
    List<String> applicationContextInitializers = SpringFactoriesLoader.loadFactoryNames(BeanInfoFactory.class, ClassUtils.getDefaultClassLoader());
    for (String applicationContextInitializer : applicationContextInitializers) {
        System.out.println(applicationContextInitializer);
    }
}

@Test
public void testLoadFactories() {
    //實例化所有在META-INF/spring.factories配置的且實現BeanInfoFactory接口的類
    List<BeanInfoFactory> beanInfoFactories = SpringFactoriesLoader.loadFactories(BeanInfoFactory.class, ClassUtils.getDefaultClassLoader());

    for (BeanInfoFactory beanInfoFactory : beanInfoFactories) {
        System.out.println(beanInfoFactory);
    }
}

通過以上可以證明,SpringFactoriesLoader會尋找jar包中配置META-INF下的spring.factories配置文件相應Key的value,並根據需要實例化。

源碼詳見:github


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM