@ComponentScan 其实就是起到了包扫描的作用。
传统方式的包扫描,是在配置文件中输入以下配置项:
<context:component-scan base-package="com.spring" use-default-filters="false"></context:component-scan>
如果不用配置文件的方式,可以直接在类上添加@ComponentScan,起到的作用和上面一样,如下所示:
@ComponentScan
public class MainConfig {
//给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
@Bean("person")
public Person person01(){
return new Person("lisi", 20);
}
}
@ComponentScan也可以指定自己需要扫描的组件,或者指定扫描时要排除的组件:
ComponentScan.Filter[] includeFilters() default {};
ComponentScan.Filter[] excludeFilters() default {};
以上两行代码是@ComponentScan中的源码,其实是两个拦截器,我们可以通过设置Value值来拦截不需要扫描的包,或者要排除的包,我们举一个includeFilters()的例子:
@ComponentScan(value = "com.springtest1",
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
classes = {Controller.class, Repository.class})},useDefaultFilters = false)
public class MainConfig {
public Person person(){
return new Person();
}
}
通过以上设置,spring的容器中只会有@Controller和@Repository标注的类名。
注意以上代码中的type = FilterType.ANNOTATION代码,它的意思是根据注解来指定要扫描或者要排除的包。除此之外,还可以根据类名来指定要扫描或者要排除的包,这两个方式是最常用的,源码中还有其他的方法,如下所示:
package org.springframework.context.annotation;
public enum FilterType {
ANNOTATION,
ASSIGNABLE_TYPE,
ASPECTJ,
REGEX,
CUSTOM;
private FilterType() {
}
}
所以在学习时,要看看底层的代码,这样我们就可以了解更多的知识。关于@ComponentScan呢,其实还要讲的是,jdk1.8支持多个@ComponentScan在同一个类上多次注解,jdk1.8以下就需要使用另外一个@ComponentScans注解了,大家自己去发现@ComponentScans注解吧。