首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从BeanDefinition获取特定的类实例

从BeanDefinition获取特定的类实例
EN

Stack Overflow用户
提问于 2022-07-04 09:54:25
回答 1查看 56关注 0票数 0

我试图使用Spring来使用以下方法查找接口的实现:

代码语言:javascript
运行
复制
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>

EN

回答 1

Stack Overflow用户

发布于 2022-07-05 08:46:52

假设生成的映射键("String comes from an annotation on the implementing classes")是AnnotationTypeFilter中使用的注释的属性,您可以这样做(省略错误处理):

代码语言:javascript
运行
复制
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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72854853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档