7.10.4 Using filters to customize scanning
默认的,被注解@Component, @Repository, @Service, @Controller,或者自己定义被@Component标记的注解标记的类都会发现作为候选的组件。然而,你可以更改拓展此行为仅仅应用自定义的过滤器。@ComponentScan注解的includeFilters或excludeFilters参数。每个过滤元素需要一个类型和表达式属性。下面的表描述了过滤的选项
Filter Type | Example Expression | Description |
---|---|---|
annotation(default) | org.example.SomeAnnotation | 目标组件类级别出现的注解 |
assignable | org.example.SomeClass | 目标组件继承(或实现)的类(或接口) |
aspectj | org.example..*Service+ | An AspectJ type expression to be matched by the target components. |
regex | org.example.Default.* | 正则表达式匹配的目标组件的类名 |
custom | org.example.MyTypeFilter | A custom implementation of the org.springframework.core.type .TypeFilter interface. |
下面的示例展示了配置:忽略@Repository注解且使用“stub”仓库
@Configuration
@ComponentScan(basePackages = "org.example",
includeFilters = @Filter(type=FilterType.REGEX, pattern = ".*Stub.*Repository"),
excludeFilters = @Filter(Repository.class))
public class AppConfig{
...
}
你可以禁止默认的过滤通过设置useDefaultFilters=false通过注解的方式或提供use-default-filters="false"作为<component-scan/>元素的属性。这将会禁止自动发现标记为@Component, @Repository, @Service, @Controller或@Configuration的类