在實際開發過程當中,咱們不可能對每一個bean都用@bean和@Configuration配合來定義bean,咱們應該要對某個包下面的bean自動掃描。
ComponentScan主要的做用,就是告訴容器,去哪裏掃描bean,把符合狀況的bean交給容器管理。若是有多個路徑,能夠用@ComponentScans
註解。
在spring學習之bean的定義中,提到了這個註解。其餘用法以下:正則表達式
<context:component-scan base-package=""/>
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan("com.***.***"); ctx.refresh();
掃描的過濾規則包括annotation註解、assignable特定類型、aspectj、regex正則表達式、custom自定義方式。
includeFilters:按照某種規則掃描組件。
excludeFilters:按照某種規則排除組件。
useDefaultFilters:true,掃描全部組件,false,自定義。spring
MyConfig2segmentfault
@Configuration @ComponentScan(value="com.learn.annotation",excludeFilters = {@ComponentScan.Filter(type =FilterType.ANNOTATION,classes = {Component.class})}) public class MyConfig2 { }
測試代碼:app
@Test public void test2() { ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig2.class); String[] names = app.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } }
運行結果:
能夠看出,註解是Component的已經被排除了。其餘幾種規則相似就不提了,下面看看自定義方式。ide
MyFilter,必須實現org.springframework.core.type .TypeFilter接口。這邊規則是包含Controller類名的類。學習
public class MyFilter implements TypeFilter { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { ClassMetadata classMetadata = metadataReader.getClassMetadata(); return classMetadata.getClassName().contains("Controller"); } }
MyConfig3測試
@Configuration @ComponentScan(value="com.learn.annotation",includeFilters = {@ComponentScan.Filter(type =FilterType.CUSTOM,classes = {MyFilter.class})},useDefaultFilters = false) public class MyConfig3 { }
測試代碼spa
@Test public void test3() { ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig3.class); String[] names = app.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } }
運行結果:code