使用ClassPathScanningCandidateComponentProvider并排除特殊目录

时间:2017-06-29 06:27:05

标签: java spring eclipse classpath scanning

我想使用ClassPathScanningCandidateComponentProvider来搜索一个类的不同子类。但在这种情况下我需要排除一个特殊目录。

示例:

目录/封装

src/main/java/frstPck/scndPck
src/test/java/frstPck/scndPck

扫描代码:

public static void example() throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(Super.class));

    Set<BeanDefinition> components = provider.findCandidateComponents("frstPck/scndPck");
    for (BeanDefinition component : components) {
        Class<?> cls = Class.forName(component.getBeanClassName());
        System.out.print(cls.getSimpleName());
    }
}

问题是,类路径扫描还会找到src/test/java的子类,而这恰好不会发生。有没有可能排除这些?

1 个答案:

答案 0 :(得分:0)

这个问题很老,但是答案可以帮助别人。

如果您的测试类名称的默认名称末尾带有“ Test”一词,则可以通过按以下名称进行过滤来排除它们:

provider.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test")))

然后它将如下所示:

public static void example() throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(Super.class));
    provider.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test")));

    Set<BeanDefinition> components = provider.findCandidateComponents("frstPck/scndPck");
    for (BeanDefinition component : components) {
        Class<?> cls = Class.forName(component.getBeanClassName());
        System.out.print(cls.getSimpleName());
    }
}