Search code examples
javaspring-bootcomponent-scan

Spring boot @ComponentScan. How to exclude all packages from scan except one subpackage or class?


@ComponentScan(
    excludeFilters = {
    @ComponentScan.Filter(
        type = FilterType.REGEX,
        pattern =
            "com.base.package.*"
    )
)

Under com.base.package. there is a class that I do not want to be excluded, how can I include this single class?


Solution

  • The key is in the regex. Let's assume you want to exclude all classes except one named MyClass. You can use a negative lookahead to exclude it from the regex match. Try the following.

    @ComponentScan(
        excludeFilters = {
        @ComponentScan.Filter(
            type = FilterType.REGEX,
            pattern =
                "(?!.*MyClass)com\\.base\\.package\\..*"
        )
    )