@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 下面 ,那么會掃描這個包下的所有類還有子包的所有類,
