0

I'd like to use the ClassPathScanningCandidateComponentProvider for searching different subclasses of one class. But I need to exclude a special directory in this case.

Example:

Directories/Packages:

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

Code for scanning:

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());
    }
}

The problem is, that the classpathscanning would also find subclasses of src/test/java and exactly this should not happen. Is there any possibility to exclude those?

  • Can't you use excludeFilters of componentScan e.g. https://stackoverflow.com/questions/18992880/exclude-component-from-componentscan ? – StanislavL Jun 29 '17 at 06:37
  • I already saw the exclude filters but I didn't find a way to use them receiving the expected solution. –  Jun 29 '17 at 07:29

1 Answers1

0

The question is old but the answer can help others.

If yours test classes names have the word "Test" at the end as the default, you can exclude them by making a filter by the name like this:

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

Then it will look like this:

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());
    }
}