下面列出了怎么用org.springframework.core.io.support.SpringFactoriesLoader的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings("unchecked")
@Substitute
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
List<T> instances;
if (type.equals(SpringApplicationRunListener.class)) {
instances = (List<T>) Arrays.asList(new EventPublishingRunListener((SpringApplication)(Object)this, new String[0])); // TODO convert args
// Error when using it, and we probably should do that at build time
//AnnotationAwareOrderComparator.sort(instances);
}
else if (type.equals(SpringBootExceptionReporter.class)) {
instances = (List<T>) Arrays.asList(DiagnosticsProvider.getFailureAnalyzers((ConfigurableApplicationContext) args[0])); // Package private
// Error when using it, and we probably should do that at build time
//AnnotationAwareOrderComparator.sort(instances);
}
else {
instances = SpringFactoriesLoader.loadFactories(type, null);
}
return instances;
}
public static List<ModuleConfiguration> loadApplicationNames(ClassLoader classLoader) {
try {
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION));
return Collections.list(urls).stream()
.map(MultiModuleConfigServicePropertySourceLocator::loadProperties)
.filter(properties -> properties.getProperty(APPLICATION_NAME_KEY) != null)
.flatMap(props -> {
String applicationName = props.getProperty(APPLICATION_NAME_KEY);
String order = props.getProperty(APPLICATION_NAME_ORDER);
return Stream.of(StringUtils.commaDelimitedListToStringArray(applicationName))
.map(name ->
new ModuleConfiguration(name, order == null ? 0 : Integer.parseInt(order)));
})
.collect(Collectors.toList());
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to load multi module configuration " +
"from location [" + SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
@Override
public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {
// 获取当前 ClassLoader
ClassLoader classLoader = event.getClass().getClassLoader();
// 候选的自动装配类名单
List<String> candidates =
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, classLoader);
// 实际的自动装配类名单
List<String> configurations = event.getCandidateConfigurations();
// 排除的自动装配类名单
Set<String> exclusions = event.getExclusions();
// 输出各自数量
System.out.printf("自动装配类名单 - 候选数量:%d,实际数量:%d,排除数量:%s\n",
candidates.size(), configurations.size(), exclusions.size());
// 输出实际和排除的自动装配类名单
System.out.println("实际的自动装配类名单:");
event.getCandidateConfigurations().forEach(System.out::println);
System.out.println("排除的自动装配类名单:");
event.getExclusions().forEach(System.out::println);
}
List<TemplateVariableProvider> getTemplateVariableProviders() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Set<String> factories = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(
TemplateVariableProvider.class, Thread.currentThread().getContextClassLoader()));
return factories.stream()
.map(new Function<String, TemplateVariableProvider>() {
@Override
public TemplateVariableProvider apply(String name) {
try {
Class<TemplateVariableProvider> instanceClass =
(Class<TemplateVariableProvider>) ClassUtils.forName(name, classLoader);
return applicationContext.getBean(instanceClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}).collect(Collectors.toList());
}
StubRepository(File repository, List<HttpServerStub> httpServerStubs,
StubRunnerOptions options) {
if (!repository.isDirectory()) {
throw new IllegalArgumentException(
"Missing descriptor repository under path [" + repository + "]");
}
this.contractConverters = SpringFactoriesLoader
.loadFactories(ContractConverter.class, null);
if (log.isTraceEnabled()) {
log.trace(
"Found the following contract converters " + this.contractConverters);
}
this.httpServerStubs = httpServerStubs;
this.path = repository;
this.options = options;
this.stubs = stubs();
this.contracts = contracts();
if (log.isTraceEnabled()) {
log.trace("Found the following contracts " + this.contracts);
}
}
public static boolean isWrapper(Type type) {
if (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
if (transformers == null) {
transformers = new ArrayList<>();
transformers.addAll(
SpringFactoriesLoader.loadFactories(WrapperDetector.class, null));
}
for (WrapperDetector transformer : transformers) {
if (transformer.isWrapper(type)) {
return true;
}
}
return false;
}
List<TemplateVariableProvider> getTemplateVariableProviders() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Set<String> factories = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(
TemplateVariableProvider.class, Thread.currentThread().getContextClassLoader()));
return factories.stream()
.map(new Function<String, TemplateVariableProvider>() {
@Override
public TemplateVariableProvider apply(String name) {
try {
Class<TemplateVariableProvider> instanceClass =
(Class<TemplateVariableProvider>) ClassUtils.forName(name, classLoader);
return applicationContext.getBean(instanceClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}).collect(Collectors.toList());
}
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
List<String> names = new ArrayList<>(SpringFactoriesLoader
.loadFactoryNames(BootstrapConfiguration.class, classLoader));
names.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(
this.environment.getProperty("spring.cloud.bootstrap.sources", ""))));
List<OrderedAnnotatedElement> elements = new ArrayList<>();
for (String name : names) {
try {
elements.add(
new OrderedAnnotatedElement(this.metadataReaderFactory, name));
}
catch (IOException e) {
continue;
}
}
AnnotationAwareOrderComparator.sort(elements);
String[] classNames = elements.stream().map(e -> e.name).toArray(String[]::new);
return classNames;
}
@Override
public void starting() {
if (executed.compareAndSet(false, true)) {
List<DefaultConfigFactory> defaultConfigs = SpringFactoriesLoader.loadFactories(DefaultConfigFactory.class, this.getClass().getClassLoader());
Map<String, Object> defaultConfig = new Hashtable<>(1);
for (DefaultConfigFactory defaultConfigFactory : defaultConfigs) {
defaultConfig.putAll(defaultConfigFactory.defaultConfig());
}
springApplication.setDefaultProperties(defaultConfig);
}
}
@Override
public void starting() {
if (executed.compareAndSet(false, true)) {
List<DefaultConfigFactory> defaultConfigs = SpringFactoriesLoader.loadFactories(DefaultConfigFactory.class, this.getClass().getClassLoader());
Map<String, Object> defaultConfig = new Hashtable<>(1);
for (DefaultConfigFactory defaultConfigFactory : defaultConfigs) {
defaultConfig.putAll(defaultConfigFactory.defaultConfig());
}
springApplication.setDefaultProperties(defaultConfig);
}
}
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
if("bootstrap".equals(env.getProperty("spring.config.name"))) {
List<EnvironmentCustomizer> environmentCustomizers =
SpringFactoriesLoader.loadFactories(EnvironmentCustomizer.class, AdminEndpointApplicationRunListener.class.getClassLoader());
if(CollectionUtils.isEmpty(environmentCustomizers)) return;
for(EnvironmentCustomizer customizer: environmentCustomizers) {
customizer.customize(env);
}
}
}
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
if("bootstrap".equals(env.getProperty("spring.config.name"))) {
List<EnvironmentCustomizer> environmentCustomizers =
SpringFactoriesLoader.loadFactories(EnvironmentCustomizer.class, AdminEndpointApplicationRunListener.class.getClassLoader());
if(CollectionUtils.isEmpty(environmentCustomizers)) return;
for(EnvironmentCustomizer customizer: environmentCustomizers) {
customizer.customize(env);
}
}
}
@Test
public void sayHello() throws Exception {
List<OrderService> services = SpringFactoriesLoader.loadFactories(OrderService.class, null);
for (OrderService service : services) {
service.getOrder("worder.");
}
}
private static Properties loadProperties(URL url) {
try {
return PropertiesLoaderUtils.loadProperties(new UrlResource(url));
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to load properties " +
"from location [" + SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
CredentialProviderRegistry(final DataManager dataManager) {
this.dataManager = dataManager;
credentialProviderFactories = SpringFactoriesLoader
.loadFactories(CredentialProviderFactory.class, ClassUtils.getDefaultClassLoader()).stream()
.collect(Collectors.toMap(CredentialProviderFactory::id, Function.identity()));
}
@Override
public Object invoke(RpcInvoker invoker, RpcInvocation invocation) {
logger.info("before acquire,"+new Date());
List<AccessLimitService> accessLimitServiceLoader = SpringFactoriesLoader.loadFactories(AccessLimitService.class, null);
if(!CollectionUtils.isEmpty(accessLimitServiceLoader)){
AccessLimitService accessLimitService=accessLimitServiceLoader.get(0);
accessLimitService.acquire(invocation);
}
Object rpcResponse=invoker.invoke(invocation);
logger.info("after acquire,"+new Date());
return rpcResponse;
}
@Test
public void test() {
List<EnvironmentPostProcessor> processorList = SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, getClass().getClassLoader());
Boolean containsApollo = !Collections2.filter(processorList, new Predicate<EnvironmentPostProcessor>() {
@Override
public boolean apply(EnvironmentPostProcessor input) {
return input instanceof ApolloApplicationContextInitializer;
}
}).isEmpty();
Assert.assertTrue(containsApollo);
}
public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath,
StubConfiguration stubsConfiguration,
MessageVerifier<?> contractVerifierMessaging) {
this.stubsConfiguration = stubsConfiguration;
this.stubRunnerOptions = stubRunnerOptions;
List<HttpServerStub> serverStubs = SpringFactoriesLoader
.loadFactories(HttpServerStub.class, null);
this.stubRepository = new StubRepository(new File(repositoryPath), serverStubs,
this.stubRunnerOptions);
AvailablePortScanner portScanner = new AvailablePortScanner(
stubRunnerOptions.getMinPortValue(), stubRunnerOptions.getMaxPortValue());
this.localStubRunner = new StubRunnerExecutor(portScanner,
contractVerifierMessaging, serverStubs);
}
private Extension[] responseTransformers() {
List<WireMockExtensions> wireMockExtensions = SpringFactoriesLoader
.loadFactories(WireMockExtensions.class, null);
List<Extension> extensions = new ArrayList<>();
if (!wireMockExtensions.isEmpty()) {
for (WireMockExtensions wireMockExtension : wireMockExtensions) {
extensions.addAll(wireMockExtension.extensions());
}
}
else {
extensions.add(new DefaultResponseTransformer(false, helpers()));
}
return extensions.toArray(new Extension[extensions.size()]);
}
protected boolean multipleStoreImplementationsDetected() {
boolean multipleModulesFound = SpringFactoriesLoader
.loadFactoryNames(AbstractStoreFactoryBean.class, resourceLoader.getClassLoader()).size() > 1;
if (multipleModulesFound) {
LOGGER.info("Multiple store modules detected. Entering strict resolution mode");
}
return multipleModulesFound;
}
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
this.environment = environment;
this.resourceLoader = resourceLoader == null ? new DefaultResourceLoader()
: resourceLoader;
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(
PropertySourceLoader.class, getClass().getClassLoader());
}
protected void loadSpringBootDataFormats(ClassLoader classloader) {
List<DataFormatConfigurator> configurators = new ArrayList<>();
// add the auto-config Jackson Java 8 module configurators
dataFormatConfiguratorJsr310.ifPresent(configurator -> configurators.add(configurator));
dataFormatConfiguratorParameterNames.ifPresent(configurator -> configurators.add(configurator));
dataFormatConfiguratorJdk8.ifPresent(configurator -> configurators.add(configurator));
// next, add any configurators defined in the spring.factories file
configurators.addAll(SpringFactoriesLoader.loadFactories(DataFormatConfigurator.class, classloader));
DataFormats.loadDataFormats(classloader, configurators);
}
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Set<String> names = new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
@Override
public String[] selectImports(AnnotationMetadata metadata) {
if (!isEnabled()) {
return new String[0];
}
AnnotationAttributes attributes = AnnotationAttributes.fromMap(
metadata.getAnnotationAttributes(this.annotationClass.getName(), true));
Assert.notNull(attributes, "No " + getSimpleName() + " attributes found. Is "
+ metadata.getClassName() + " annotated with @" + getSimpleName() + "?");
// Find all possible auto configuration classes, filtering duplicates
List<String> factories = new ArrayList<>(new LinkedHashSet<>(SpringFactoriesLoader
.loadFactoryNames(this.annotationClass, this.beanClassLoader)));
if (factories.isEmpty() && !hasDefaultFactory()) {
throw new IllegalStateException("Annotation @" + getSimpleName()
+ " found, but there are no implementations. Did you forget to include a starter?");
}
if (factories.size() > 1) {
// there should only ever be one DiscoveryClient, but there might be more than
// one factory
this.log.warn("More than one implementation " + "of @" + getSimpleName()
+ " (now relying on @Conditionals to pick one): " + factories);
}
return factories.toArray(new String[factories.size()]);
}
protected void loadSpringBootDataFormats(ClassLoader classloader) {
List<DataFormatConfigurator> configurators = new ArrayList<>();
// add the auto-config Jackson Java 8 module configurators
dataFormatConfiguratorJsr310.ifPresent(configurator -> configurators.add(configurator));
dataFormatConfiguratorParameterNames.ifPresent(configurator -> configurators.add(configurator));
dataFormatConfiguratorJdk8.ifPresent(configurator -> configurators.add(configurator));
// next, add any configurators defined in the spring.factories file
configurators.addAll(SpringFactoriesLoader.loadFactories(DataFormatConfigurator.class, classloader));
DataFormats.loadDataFormats(classloader, configurators);
}
public MagicPropertySourcePostProcessor() {
this.resourceLoader = new DefaultResourceLoader();
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
}
@Test
public void test() {
// Should not throw exception
SpringFactoriesLoader.loadFactories(CfEnvProcessor.class, getClass().getClassLoader());
}
private void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
List<String> feignClients = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
// 如果 spring.factories 里为空
if (feignClients.isEmpty()) {
return;
}
for (String className : feignClients) {
try {
Class<?> clazz = beanClassLoader.loadClass(className);
AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(clazz, FeignClient.class);
if (attributes == null) {
continue;
}
// 如果已经存在该 bean,支持原生的 Feign
if (registry.containsBeanDefinition(className)) {
continue;
}
registerClientConfiguration(registry, getClientName(attributes), attributes.get("configuration"));
validate(attributes);
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
definition.addPropertyValue("url", getUrl(attributes));
definition.addPropertyValue("path", getPath(attributes));
String name = getName(attributes);
definition.addPropertyValue("name", name);
// 兼容最新版本的 spring-cloud-openfeign,尚未发布
StringBuilder aliasBuilder = new StringBuilder(18);
if (attributes.containsKey("contextId")) {
String contextId = getContextId(attributes);
aliasBuilder.append(contextId);
definition.addPropertyValue("contextId", contextId);
} else {
aliasBuilder.append(name);
}
definition.addPropertyValue("type", className);
definition.addPropertyValue("decode404", attributes.get("decode404"));
definition.addPropertyValue("fallback", attributes.get("fallback"));
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
// alias
String alias = aliasBuilder.append("FeignClient").toString();
// has a default, won't be null
boolean primary = (Boolean)attributes.get("primary");
beanDefinition.setPrimary(primary);
String qualifier = getQualifier(attributes);
if (StringUtils.hasText(qualifier)) {
alias = qualifier;
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[] { alias });
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public StubDownloaderBuilderProvider() {
this.builders.addAll(
SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null));
}