spring学习之ComponentScan

ComponentScan

在实际开发过程当中,咱们不可能对每一个bean都用@bean和@Configuration配合来定义bean,咱们应该要对某个包下面的bean自动扫描。
ComponentScan主要的做用,就是告诉容器,去哪里扫描bean,把符合状况的bean交给容器管理。若是有多个路径,能够用@ComponentScans注解。
spring学习之bean的定义中,提到了这个注解。其余用法以下:正则表达式

  1. XML配置,<context:component-scan base-package=""/>
  2. 上下文中扫描,再刷新。
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.***.***");
ctx.refresh();

扫描规则

扫描的过滤规则包括annotation注解、assignable特定类型、aspectj、regex正则表达式、custom自定义方式。
includeFilters:按照某种规则扫描组件。
excludeFilters:按照某种规则排除组件。
useDefaultFilters:true,扫描全部组件,false,自定义。spring

excludeFilters

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);
    }
}

运行结果:
image.png
能够看出,注解是Component的已经被排除了。其余几种规则相似就不提了,下面看看自定义方式。ide

custom自定义方式

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);
    }
}

运行结果:
image.pngcode

相关文章
相关标签/搜索