Search code examples
javaspringcomponent-scan

Spring cannot include/exclude beans using filters of type REGEX with an asterisk in @ComponentScan


I am trying to manage the beans my spring application loads using IncludeFilters property of @ComponentScan annotation. I use filter of type FilterType.REGEX. I would like to match anything as the last part of my pattern using but I seems not to work that way at all. I have a bean definitions:

package org.example.child;

public class ChildDao {}
...
public class ChildService{}
...
public class ChildComponent{}

and configuration class definition:

@ComponentScan(
        value = "com.example", 
        includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, 
                pattern = "com.example.*.Child*")})

With such a configuration, Spring does not find any bean at all.

When asterisk is used to match not the very last part of the pattern but is used somewhere in between, then it seems to work without a problem.

For example, following configuration matches all the Services without a problem:

@ComponentScan(
        value = "com.example", 
        includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, 
                pattern = "com.example.*.*Service")})

Is this a designed behaviour of the framework or should it be possible to match the last part of the pattern using such an 'ant like' regex pattern?


Solution

  • Filters of type FilterType.REGEX are matched using standard java Pattern and Matcher, so no ant-like patterns like "com.example.*.Child*" would match. The only reason why "com.example.*.*Service" is because of the .* which matches any sequence of characters. In order to include/exlude using regex use valid regex.

    Edit:

    So in this case, one possible option would be to use pattern like com.example.child.Child.* to match any classes from com.example.child package starting with the Child in their names.