1
我想知道是否有類似於標準SDK API的ServiceLoader
類的Spring模擬器。如果有這樣的課程,它是如何使用的?Spring中是否有ServiceLoader的模擬以及如何使用它?
請指教!
我想知道是否有類似於標準SDK API的ServiceLoader
類的Spring模擬器。如果有這樣的課程,它是如何使用的?Spring中是否有ServiceLoader的模擬以及如何使用它?
請指教!
假設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);
}
}
}
}