Spring - Using Filters To Customize Scanning with @ComponentScan

[Last Updated: May 6, 2021]

By default, @ComponentScan scans all classes which are annotated with @Component, @Repository, @Service, @Controller, @Configuration, or a custom annotation that itself is annotated with @Component.

We can modify and extend this behavior by applying custom filters via @ComponentScan#includeFilters or @ComponentScan#excludeFilters attributes.

Following shows ComponentScan annotation snippet along with include/exclude filter attributes and their type (i.e. Filter) definition:

package org.springframework.context.annotation;
public @interface ComponentScan {
    ComponentScan.Filter[] includeFilters() default {};

    ComponentScan.Filter[] excludeFilters() default {};

    public @interface Filter {
        FilterType type() default FilterType.ANNOTATION;

        Class<?>[] value() default {};

        Class<?>[] classes() default {};

        String[] pattern() default {};

Following shows FilterType snippet:

package org.springframework.context.annotation;

public enum FilterType {
    public enum FilterType {
	//Filter candidates marked with a given annotation.
	//Filter candidates assignable to a given type.
        //Filter candidates matching a given AspectJ type pattern expression.
        //Filter candidates matching a given regex pattern.

	//Filter candidates using a given custom TypeFilter implementation.

In next tutorials we will see the example of each (except for ASPECJ which is outside the sope of these tutorials).

See Also