spring 使用 java 配置时,默认只将扫描路径中带有 @Component
, @Repository
, @Service
, @Controller
, @Configuration
注解的类作为 bean 的定义。
除此之外,还可以通过 @ComponentScan
注解的includeFilters
和excludeFilters
来指定。
例如:
@Configuration
@ComponentScan(basePackages = "org.example",
includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
excludeFilters = @Filter(Repository.class))
public class AppConfig {
// ...
}
@Filter
的类型如下:
类型 | 描述 |
---|---|
注解(默认) | 将带有指定注解的类作为 bean 定义 |
assignable | 指定具体的类(对子类和子接口同样有效) |
aspectj | 以 aspectJ 表达式的形式指定类 |
regex | 以正则表达式的情况指定类 |
custom | 指定一个自定义的类作为 filter ,这个类实现了 Filter 接口 |