如何通过classpath中的多个注释查找类?

时间:2015-04-09 14:21:38

标签: java spring spring-boot

我想从类路径中找到所有定义了两个注释的类。

通常当需要其中一个注释时,我可以按照以下方式查找它们( OR 匹配):

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
provider.addIncludeFilter(new AnnotationTypeFilter(CustomAnnotation.class));
Set<BeanDefinition> beans = provider.findCandidateComponents("com.xyz.abc");

如果我需要 AND 匹配,我必须更改哪些内容,以便只返回两个注释的类?

1 个答案:

答案 0 :(得分:2)

您是否考虑过创建自己的过滤器?类似的东西:

final TypeFilter entityFilter = new AnnotationTypeFilter(Entity.class);
final TypeFilter customFilter = new AnnotationTypeFilter(CustomAnnotation.class);
TypeFilter andFilter = new TypeFilter {
    boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        return entityFilter.match(metadataReader, metadataReaderFactory) && customFilter.match(metadataReader, metadataReaderFactory);
    }
};
provider.addIncludeFilter(andFilter);