@ComponentScan
目录
- 作用
- 属性讲解
- 扫描的路径
1. 作用
主要是从定义的扫描路径中,找出标识了需要装配的类自动装配大spring 的bean容器中。
2. 属性详解
@ComponentScan的源代码
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Repeatable(ComponentScans.class) public @interface ComponentScan { /** * 对应的包扫描路径 可以是单个路径,也可以是扫描的路径数组 * @return */ @AliasFor("basePackages") String[] value() default {}; /** * 和value一样是对应的包扫描路径 可以是单个路径,也可以是扫描的路径数组 * @return */ @AliasFor("value") String[] basePackages() default {}; /** * 指定具体的扫描的类 * @return */ Class<?>[] basePackageClasses() default {}; /** * 对应的bean名称的生成器 默认的是BeanNameGenerator * @return */ Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class; /** * 处理检测到的bean的scope范围 */ Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class; /** * 是否为检测到的组件生成代理 * Indicates whether proxies should be generated for detected components, which may be * necessary when using scopes in a proxy-style fashion. * <p>The default is defer to the default behavior of the component scanner used to * execute the actual scan. * <p>Note that setting this attribute overrides any value set for {@link #scopeResolver}. * @see ClassPathBeanDefinitionScanner#setScopedProxyMode(ScopedProxyMode) */ ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT; /** * 控制符合组件检测条件的类文件 默认是包扫描下的 **/*.class * @return */ String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN; /** * 是否对带有@Component @Repository @Service @Controller注解的类开启检测,默认是开启的 * @return */ boolean useDefaultFilters() default true; /** * 指定某些定义Filter满足条件的组件 FilterType有5种类型如: * ANNOTATION, 注解类型 默认 ASSIGNABLE_TYPE,指定固定类 ASPECTJ, ASPECTJ类型 REGEX,正则表达式 CUSTOM,自定义类型 * @return */ Filter[] includeFilters() default {}; /** * 排除某些过来器扫描到的类 * @return */ Filter[] excludeFilters() default {}; /** * 扫描到的类是都开启懒加载 ,默认是不开启的 * @return */ boolean lazyInit() default false; }
总结一下@ComponentScan的常用方式如下
- 自定扫描路径下边带有@Controller,@Service,@Repository,@Component注解加入spring容器
- 通过includeFilters加入扫描路径下没有以上注解的类加入spring容器
- 通过excludeFilters过滤出不用加入spring容器的类
- 自定义增加了@Component注解的注解方式
3. 扫描的路径
@ComponentScan 如果不设置basePackage的话 默认会扫描包的所有类,所以最好还是写上basePackage ,减少加载时间。
默认扫描*/.class路径
比如这个注解在com.first.springbootproject.springboot 下面 ,那么会扫描这个包下的所有类还有子包的所有类,
