當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring - @CompentScan全解
生活随笔
收集整理的這篇文章主要介紹了
Spring - @CompentScan全解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 基本使用
- excludeFilters
- includeFilters
- @ComponentScan.Filter
- 4種類型
- 自定義FilterType
基本使用
在配置類上寫@CompentScan注解來進行包掃描
@Configuration @ComponentScan(basePackages = {"com.artisan"}) public class MainConfig {}excludeFilters
@Configuration @ComponentScan(basePackages = {"com.artisan"},excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {ArtisanService.class}) }) public class MainConfig { }這里會 排除標注了@Controller注解 和 特定的ArtisanService ,不會被加載到IOC容器中。
includeFilters
若使用包含的用法, 需要把useDefaultFilters屬性設置為false(true表示掃描全部的)
@Configuration @ComponentScan(basePackages = {"com.artisan"},includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class}) },useDefaultFilters = false) public class MainConfig { }@ComponentScan.Filter
4種類型
-
注解形式的FilterType.ANNOTATION 比如@Controller @Service @Repository @Compent
-
指定類型的 FilterType.ASSIGNABLE_TYPE
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {ArtisanService.class}) -
aspectj類型的 FilterType.ASPECTJ(不常用)
-
正則表達式的 FilterType.REGEX(不常用)
-
自定義的 FilterType.CUSTOM
自定義FilterType
import org.springframework.core.io.Resource; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.ClassMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.TypeFilter;import java.io.IOException;public class ArtisanFilterType implements TypeFilter {@Overridepublic boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {//獲取當前類的注解源信息AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();//獲取當前類的class的源信息ClassMetadata classMetadata = metadataReader.getClassMetadata();//獲取當前類的資源信息Resource resource = metadataReader.getResource();System.out.println("類的路徑:"+classMetadata.getClassName());if(classMetadata.getClassName().contains("dao")) {return true;}return false;} }引用自定義類型的Filter
@ComponentScan(basePackages = {"com.tuling.testcompentscan"},excludeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM,value = ArtisanFilterType.class) },includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Repository.class) })測試的話,打印下beanDefinition 即可
public class MainClass {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);String[] beanDefinationNames = ctx.getBeanDefinitionNames();for (String name:beanDefinationNames) {System.out.println("bean的定義信息:"+name);}} }總結
以上是生活随笔為你收集整理的Spring - @CompentScan全解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式 -行为型模式_ 观察者模式Ob
- 下一篇: Spring - @Conditiona