转自:
下文笔者讲述Spring中ComponentScan注解的简介说明,如下所示:
ComponentScan注解的功能
定义的扫描路径,把符合扫描规则的类装配到spring的bean容器中
ComponentScan注解的源码
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Repeatable(ComponentScans.class) public @interface ComponentScan { @AliasFor("basePackages") String[] value() default {}; @AliasFor("value") String[] basePackages() default {}; Class[] basePackageClasses() default {}; Class nameGenerator() default BeanNameGenerator.class; Class scopeResolver() default AnnotationScopeMetadataResolver.class; ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT; String resourcePattern() default "**/*.class"; boolean useDefaultFilters() default true; ComponentScan.Filter[] includeFilters() default {}; ComponentScan.Filter[] excludeFilters() default {}; boolean lazyInit() default false; @Retention(RetentionPolicy.RUNTIME) @Target({}) public @interface Filter { FilterType type() default FilterType.ANNOTATION; @AliasFor("classes") Class[] value() default {}; @AliasFor("value") Class[] classes() default {}; String[] pattern() default {}; } } basePackages与value:? 用于指定包的路径,进行扫描 basePackageClasses: 用于指定某个类的包的路径进行扫描 nameGenerator: bean的名称的生成器 useDefaultFilters: 是否开启对@Component,@Repository,@Service,@Controller的类进行检测 includeFilters: 包含的过滤条件 FilterType.ANNOTATION:按照注解过滤, FilterType.ASSIGNABLE_TYPE:按照给定的类型, FilterType.ASPECTJ:使用ASPECTJ表达式, FilterType.REGEX:正则, FilterType.CUSTOM:自定义规则 excludeFilters: 排除的过滤条件,用法和includeFilters一样
注解示例分享
扫描包 @ComponentScan(basePackages ="") //单个 @ComponentScan(basePackages = {"xxx","com.java265.","..."}) //多个 注意:可以省略“basePackages =” @Configuration @ComponentScan("com.java265.spring.service") public class MyConfig {} @Configuration @ComponentScan("com.java265.spring.dao","com.java265.spring.service") public class MyConfig {} @Configuration @ComponentScan("com.java265.spring.*") //通配符匹配所有的包 public class MyConfig {} 2. 扫描类 @ComponentScan(basePackageClasses ="") //单个 @ComponentScan(basePackageClasses = {"aaa","bbb","…"}) //多个 注意:不可以省略“basePackageClasses =” @Configuration @ComponentScan(basePackageClasses = HelloController.class) public class MyConfig { }
Spring ComponentScan注解有以下特性
1.自定扫描路径下边带有@Controller,@Service,@Repository,@Component注解加入spring容器
2.通过includeFilters加入扫描路径下没有以上注解的类加入spring容器
3.通过excludeFilters过滤出不用加入spring容器的类
4.自定义增加了@Component注解的注解方式