How do Spring’s include-filter and exclude-filter work?

  java, question

How do Spring’s include-filter and exclude-filter work?
Exclude-filter seems to filter out unqualified components and does not load, but include-filter does not load only some components. Can you explain the mechanism of the two in detail?

Let’s look at some properties of component-scan.

  • Base Packages: The name of the basePackages:Spring will scan, and Spring will scan all classes under the package and its descendants

  • UseDefaultFilters: The default is true, when Spring scans the class, it finds that if it is marked as@Component@Repository@Service@ControllerIt is automatically instantiated as a bean and added to the context. if set to false, Spring ignores it even if it is labeled @Component or something else.

  • IncludeFilters specifies the type to instantiate when scanning. We can see from the name that this is a Filter. You can define this Filter yourself. Spring provides us with a convenient implementation. We can decide whether to instantiate this class when scanning this class according to relevant information such as labels, classes, packages, etc. Note that if you only want to scan such as@ControllerNot only includeFilters, but also set useDefaultFilters to false.

  • ExcludeFilter specifies that a class needs to be ignored when scanning it. The implementation is the same as the previous Filter, except that Spring will ignore the class if the filters match.

In this way, the behavior of includeFilters and excludeFilters is very clear. Spring will pass includeFilters and exclude Filters for each class scanned. if a filter matches, the corresponding operation will be executed (instantiated or ignored)