我试图使用Spring来使用以下方法查找接口的实现:
public static Set<BeanDefinition> getImplementations(String packageName, Class<? extends Annotation> annotation) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(annotation));
return provider.findCandidateComponents(packageName);
}这确实有效,并且找到了我的实现类(在指定的包中进行注释)。但是,我的最终目标是创建一个Map<String, Class<?>>,其中String来自于实现类的注释,而Class本身就是实现者。如何从beanDefinition实例获得注释和类?如果这是不可能的(很容易),我如何才能创建一个Map<String, Class<?>>或Map<String, Implementer>从我的Set<BeanDefinition>
发布于 2022-07-05 08:46:52
假设生成的映射键("String comes from an annotation on the implementing classes")是AnnotationTypeFilter中使用的注释的属性,您可以这样做(省略错误处理):
public Set<BeanDefinition> getImplementations(String packageName,
Class<? extends Annotation> annotation) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(annotation));
return provider.findCandidateComponents(packageName);
}
public Map<String, Class<?>> getImplementationsMap(String packageName,
Class<? extends Annotation> annotation,
String annotationAttribute) {
return getImplementations(packageName, annotation).stream()
.collect(Collectors.toMap(beanDefinition -> extractAnnotationAttribute(beanDefinition, annotation, annotationAttribute),
beanDefinition -> extractBeanClass(beanDefinition)));
}
private Class<?> extractBeanClass(BeanDefinition beanDefinition) {
try {
return ((ScannedGenericBeanDefinition) beanDefinition)
.resolveBeanClass(this.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
}
private String extractAnnotationAttribute(BeanDefinition beanDefinition,
Class<? extends Annotation> annotation,
String annotationAttribute) {
return ((ScannedGenericBeanDefinition) beanDefinition)
.getMetadata()
.getAnnotationAttributes(annotation.getName())
.get(annotationAttribute).toString();
}https://stackoverflow.com/questions/72854853
复制相似问题