gpt4 book ai didi

java - Spring 中是否有 ServiceLoader 的类似物以及如何使用它?

转载 作者:行者123 更新时间:2023-11-30 07:08:07 28 4
gpt4 key购买 nike

我试图找出是否有 ServiceLoader 类的 Spring 类似物,它是标准 SDK API 的一部分。如果有这样的类怎么用?

请指教!

最佳答案

假设 SpringFactoriesLoader 适合您。从它的 JavaDocs:

/*
* General purpose factory loading mechanism for internal use within the framework.
*
* <p>The {@code SpringFactoriesLoader} loads and instantiates factories of a given type
* from "META-INF/spring.factories" files. The file should be in {@link Properties} format,
* where the key is the fully qualified interface or abstract class name, and the value
* is a comma-separated list of implementation class names. For instance:
*
* <pre class="code">example.MyService=example.MyServiceImpl1,example.MyServiceImpl2</pre>
*
* where {@code MyService} is the name of the interface, and {@code MyServiceImpl1} and
* {@code MyServiceImpl2} are the two implementations.
*/

我们项目之一的示例:

META-INF/spring.factories:

org.springframework.integration.config.IntegrationConfigurationInitializer=\
org.springframework.integration.config.GlobalChannelInterceptorInitializer,\
org.springframework.integration.config.IntegrationConverterInitializer

实现:

public class IntegrationConfigurationBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Set<String> initializerNames = new HashSet<String>(
SpringFactoriesLoader.loadFactoryNames(IntegrationConfigurationInitializer.class, beanFactory.getBeanClassLoader()));

for (String initializerName : initializerNames) {
try {
Class<?> instanceClass = ClassUtils.forName(initializerName, beanFactory.getBeanClassLoader());
Assert.isAssignable(IntegrationConfigurationInitializer.class, instanceClass);
IntegrationConfigurationInitializer instance = (IntegrationConfigurationInitializer) instanceClass.newInstance();
instance.initialize(beanFactory);
}
catch (Exception e) {
throw new IllegalArgumentException("Cannot instantiate 'IntegrationConfigurationInitializer': " + initializerName, e);
}
}
}

}

关于java - Spring 中是否有 ServiceLoader 的类似物以及如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248025/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com