下面列出了org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
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;
}
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;
}
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()]);
}
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();
}
}
}
@Override
protected List<String> doSelect(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> classNames = new ArrayList<String>();
//store 在BootCommonServiceConfig之前初始化,因为BootCommonService依赖filestore来加载
classNames.add(OssConfiguration.class.getName());
classNames.add(CosConfiguration.class.getName());
if(attributes.getBoolean("enableCommonService")){
classNames.add(BootCommonServiceConfig.class.getName());
}
classNames.add(BootFixedConfiguration.class.getName());
AppcationType appcationType = (AppcationType)attributes.get("appcationType");
if(appcationType==AppcationType.WEB_SERVICE){
classNames.add(BootMSContextAutoConfig.class.getName());
}else if(appcationType==AppcationType.WEB_UI){
classNames.add(BootWebUIContextAutoConfig.class.getName());
}
classNames.add(ExcelViewConfiguration.class.getName());
classNames.add(CorsFilterConfiguration.class.getName());
classNames.add(BootDbmConfiguration.class.getName());
classNames.add(ErrorHandleConfiguration.class.getName());
classNames.add(EnhanceRequestMappingConfiguration.class.getName());
classNames.add(JwtContextConfig.class.getName());
classNames.add(OAuth2SsoClientAutoContextConfig.class.getName());
classNames.add(RedisConfiguration.class.getName());
classNames.add(AsyncMvcConfiguration.class.getName());
classNames.add(AsyncTaskConfiguration.class.getName());
classNames.add(AccessLogConfiguration.class.getName());
classNames.add(GraceKillConfiguration.class.getName());
//cache
classNames.add(SpringCacheConfiguration.class.getName());
classNames.add(RedissonConfiguration.class.getName());
//swagger
classNames.add(SwaggerConfiguration.class.getName());
//activemq
classNames.add("org.onetwo.boot.module.activemq.ActivemqConfiguration");
//session
classNames.add(BootSpringSessionConfiguration.class.getName());
Collection<String> exts = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(this.annotationClass, this.beanClassLoader));
for(String extClassName : exts){
Class<?> extClass;
try {
extClass = ClassUtils.forName(extClassName, beanClassLoader);
} catch (ClassNotFoundException | LinkageError e) {
throw new BaseException("load "+this.annotationClass.getSimpleName()+" error. extension class: " + extClassName, e);
}
if(extClass.getAnnotation(JFishWebPlugin.class)==null){
throw new BaseException("extension class["+extClassName+"] must be annotated by "+JFishWebPlugin.class.getName());
}
classNames.add(extClassName);
}
return classNames;
}
@Test
public void test(){
List<String> names = SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, ClassUtils.getDefaultClassLoader());
System.out.println("names:"+names);
}
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
List<String> factories = SpringFactoriesLoader.loadFactoryNames(ProjectGenerationConfiguration.class,
getClass().getClassLoader());
return factories.toArray(new String[0]);
}
/**
* Get the names of the default {@link TestExecutionListener} classes for
* this bootstrapper.
* <p>The default implementation looks up all
* {@code org.springframework.test.context.TestExecutionListener} entries
* configured in all {@code META-INF/spring.factories} files on the classpath.
* <p>This method is invoked by {@link #getDefaultTestExecutionListenerClasses()}.
* @return an <em>unmodifiable</em> list of names of default {@code TestExecutionListener}
* classes
* @see SpringFactoriesLoader#loadFactoryNames
*/
protected List<String> getDefaultTestExecutionListenerClassNames() {
List<String> classNames =
SpringFactoriesLoader.loadFactoryNames(TestExecutionListener.class, getClass().getClassLoader());
if (logger.isInfoEnabled()) {
logger.info(String.format("Loaded default TestExecutionListener class names from location [%s]: %s",
SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION, classNames));
}
return Collections.unmodifiableList(classNames);
}
/**
* Get the names of the default {@link TestExecutionListener} classes for
* this bootstrapper.
* <p>The default implementation looks up all
* {@code org.springframework.test.context.TestExecutionListener} entries
* configured in all {@code META-INF/spring.factories} files on the classpath.
* <p>This method is invoked by {@link #getDefaultTestExecutionListenerClasses()}.
* @return an <em>unmodifiable</em> list of names of default {@code TestExecutionListener}
* classes
* @see SpringFactoriesLoader#loadFactoryNames
*/
protected List<String> getDefaultTestExecutionListenerClassNames() {
List<String> classNames =
SpringFactoriesLoader.loadFactoryNames(TestExecutionListener.class, getClass().getClassLoader());
if (logger.isInfoEnabled()) {
logger.info(String.format("Loaded default TestExecutionListener class names from location [%s]: %s",
SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION, classNames));
}
return Collections.unmodifiableList(classNames);
}
/**
* Get the names of the default {@link TestExecutionListener} classes for
* this bootstrapper.
* <p>The default implementation looks up all
* {@code org.springframework.test.context.TestExecutionListener} entries
* configured in all {@code META-INF/spring.factories} files on the classpath.
* <p>This method is invoked by {@link #getDefaultTestExecutionListenerClasses()}.
* @return an <em>unmodifiable</em> list of names of default {@code TestExecutionListener}
* classes
* @see SpringFactoriesLoader#loadFactoryNames
*/
protected List<String> getDefaultTestExecutionListenerClassNames() {
final List<String> classNames = SpringFactoriesLoader.loadFactoryNames(TestExecutionListener.class,
getClass().getClassLoader());
if (logger.isInfoEnabled()) {
logger.info(String.format("Loaded default TestExecutionListener class names from location [%s]: %s",
SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION, classNames));
}
return Collections.unmodifiableList(classNames);
}