@ComponentScans
@ComponentScans源码如下
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface ComponentScans {
ComponentScan[] value();
}
- 这里可以看到ComponentScans下面就一个ComponentScan一个属性
@ComponentScan说明
-
@ComponentScan注解用于配置组件扫描,在spring xml配置文件中用context:component-scan标签来表示。可以配置basePackageClasses()或basePackages()来定义要扫描的特定包,如果未定义,则从声明此注解的类的包中扫描(组件注解包括@Controller、@Service、@Component等)。
-
@ComponentScan有如下属性:
- value ,指定要扫描的package;
- includeFilters=Filter[]:指定只包含的组件;
- excludeFilters=Filter[]:指定需要排除的组件;
- useDefaultFilters=true/false:指定是否需要使用Spring默认的扫描规则 语法;
1. value
- 用于配置扫描被注解的组件的包
- 例如:
@ComponentScan(basePackages={"com.fullexception.controller","com.fullexception.service"})
- 指定扫描com.fullexception.controller和com.fullexception.service包。
2. includeFilters=Filter[]
- 指定只包含的组件
- 例如:这里是扫描包中带有Controller注解的类
@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
3. excludeFilters = Filter[]
- 排除包含的组件
- useDefaultFilters=false,让spring默认过滤规则失效。
- 例如:排除扫描包中的Controller注解类
@ComponentScans({
@ComponentScan(value="com.hobart.spring",excludeFilters ={
@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
},useDefaultFilters=false)
})
4. @Filter的分类分类
- FilterType.ANNOTATION :按照注解
- FilterType.ASSIGNABLE_TYPE :按照给定的类型
- FilterType.ASPECTJ :使用Aspectj表达式
- FilterType.REGEX :按照正则表达式
- FilterType.CUSTOM :自定义Filter
@ComponentScans(
value = {
@ComponentScan(value = "com.atguigu", includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
}, useDefaultFilters = false)
}
)
//@ComponentScan value:指定要扫描的包
//excludeFilters = Filter[] :指定扫描的时候按照什么规则排除那些组件
//includeFilters = Filter[] :指定扫描的时候只需要包含哪些组件
//FilterType.ANNOTATION:按照注解
//FilterType.ASSIGNABLE_TYPE:按照给定的类型;
//FilterType.ASPECTJ:使用ASPECTJ表达式
//FilterType.REGEX:使用正则指定
//FilterType.CUSTOM:使用自定义规则
public class MyMainConfig {
@Bean
public Student student() {
return new Student();
}
}