@ComponentScan使用场景

一、简单介绍

翻开Spring的源码找到@ComponentScan注解的源码,发现注解类上赫然标注着Since: 3.1字样。也就是说,@ComponentScan注解是从Spring的3.1版本开始提供的。在@ComponentScan注解上,标注了一个@Repeatable注解,@Repeatable注解的属性值为ComponentScans.class。再次翻看下@ComponentScans注解的源码,类上标注着Since: 4.3字样。也就是说,@ComponentScans注解是从Spring4.3版本开始提供的。@ComponentScans注解就相当于是@ComponentScan注解的一个数组,在@ComponentScans注解中可以多次使用@ComponentScan注解来扫描不同的包路径。

二、注解说明

@ComponentScans注解可以看作是@ComponentScan注解的一个数组,在@ComponentScans注解中可以多次标注@ComponentScan注解。

@ComponentScan注解最核心的功能就是Spring IOC容器在刷新的时候会扫描对应包下标注了@Component注解、@Configuration注解、@Repository注解、@Service注解和@Controller等等注解的类,生成扫描到的类的Bean定义信息,整体流程与注册ConfigurationClassPostProcessor类的Bean定义信息的流程基本一致,最终都会将其保存到BeanFactory中的beanDefinitionMap中。

1. @ComponentScans注解源码

/***
 * @author Juergen Hoeller
 * @since 4.3
 * @see ComponentScan
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ComponentScans {
 ComponentScan[] value();
}

可以看到,@ComponentScans注解的源码还是比较简单的,在@ComponentScans注解中存在一个ComponentScan[]数组类型的value属性,说明@ComponentScans注解的属性可以存放一个@ComponentScan注解类型的数组,可以在ComponentScans注解中多次添加@ComponentScan注解。从@ComponentScans注解的源码还可以看出,@ComponentScans注解从Spring 4.3版本开始提供。

2. @ComponentScan注解源码

/*
 * @author Chris Beams
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 3.1
 * @see Configuration
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {

 @AliasFor("basePackages")
 String[] value() default {};

 @AliasFor("value")
 String[] basePackages() default {};

 Class<?>[] basePackageClasses() default {};

 Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

 Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;

 ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;

 String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN;

 boolean useDefaultFilters() default true;

 Filter[] includeFilters() default {};

 Filter[] excludeFilters() default {};

 boolean lazyInit() default false;

 @Retention(RetentionPolicy.RUNTIME)
 @Target({})
 @interface Filter {

  FilterType type() default FilterType.ANNOTATION;

  @AliasFor("classes")
  Class<?>[] value() default {};

  @AliasFor("value")
  Class<?>[] classes() default {};

  String[] pattern() default {};

 }
}

可以看到,Spring从3.1版本开始提供@ComponentScan注解,@ComponentScan注解中还有一个内部注解@Filter。

@ComponentScan注解中的每个属性的含义如下所示:

  • value:作用同basePackages属性,String[]数组类型,指定要扫描的包名。如果指定了要扫描的包名,则Spring会扫描指定的包及其子包下的所有类。
  • basePackages:作用同value属性,String[]数组类型,指定要扫描的包名。如果指定了要扫描的包名,则Spring会扫描指定的包及其子包下的所有类。
  • basePackageClasses:Class<?>[]数组类型,指定要扫描的类的Class对象。该类所在包及其子包下的其他类也会被扫描并注入IOC容器。(例如:@ComponentScan(basePackageClasses = UserService.class),则UserService所在包及其子包下的其他类也会被扫描)
  • nameGenerator:Class<? extends BeanNameGenerator>类型,指定扫描类时,向IOC注入Bean对象时的命名规则。
  • scopeResolver:Class<? extends ScopeMetadataResolver>类型,扫描类时,用于处理并转换符合条件的Bean的作用范围。
  • scopedProxy:ScopedProxyMode类型,指定生成Bean对象时的代理方式,默认的代理方法是DEFAULT,也就是不使用代理。关于ScopedProxyMode的更多详细的内容,参见后面章节。
  • resourcePattern:String类型,用于指定扫描的文件类型,默认是扫描指定包下的**/.class(**表示当前包及其子包,/.class表示任意类名的字节码)。
  • useDefaultFilters:boolean类型,是否自动检测@Component @Repository @Service @Controller注解,默认是true。
  • includeFilters:Filter[]数组类型,自定义组件扫描过滤规则,符合过滤规则的类的Bean定义信息会被注册到IOC容器中。
    includeFilters表示只包含对应的规则,当使用includeFilters()来指定只包含哪些注解标注的类时,需要禁用默认的过滤规则,也就是需要将useDefaultFilters属性设置为false。并且,除了符合过滤规则的类外,Spring内置的如下名称的类的Bean定义信息注册到IOC容器时不受过滤规则限制,如下所示:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
  • excludeFilters:Filter[]数组类型,自定义组件扫描过滤规则,excludeFilters表示排除使用对应的规则,符合过滤规则的类的Bean定义信息不会被注册到IOC容器中。
  • lazyInit:boolean类型,从Spring4.1版本开始提供,表示Spring扫描组件时是否采用懒加载 ,默认false,表示不开启懒加载。

@Filter注解中的每个属性的含义如下所示:

  • type:FilterType类型,表示过滤规则的类型。关于FilterType的更多详细的内容,参见后面章节。
  • value:Class<?>[]数组类型,过滤符合规则的类,作用同classes属性。
  • classes:Class<?>[]数组类型,过滤符合规则的类,作用同value属性。
  • pattern:如果FilterType取值为ASPECTJ,则此属性表示ASPECTJ表达式。

3. ScopedProxyMode枚举类源码

ScopedProxyMode枚举类表示Spring指定生成Bean对象时的代理方式

/*
 * @author Mark Fisher
 * @since 2.5
 * @see ScopeMetadata
 */
public enum ScopedProxyMode {
 DEFAULT,
 NO,
 INTERFACES,
 TARGET_CLASS
}

ScopedProxyMode类是从Spring 2.5版本开始提供的枚举类,每个属性的含义如下所示。

  • DEFAULT:默认的代理方式,也就是不使用代理,除非在component-scan级别使用了不同的配置。
  • NO:不使用代理。
  • INTERFACES:基于JDK动态代理实现接口代理对象。
  • TARGET_CLASS:基于CGLib动态代理创建类代理对象。

4. FilterType枚举类源码

FilterType枚举类表示Spring扫描类时的过滤类型

/*
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @author Chris Beams
 * @since 2.5
 */
public enum FilterType {
 ANNOTATION,
 ASSIGNABLE_TYPE,
 ASPECTJ,
 REGEX,
 CUSTOM
}

FilterType类是Spring2.5版本开始提供的枚举类,每个属性的含义如下所示。

  • ANNOTATION:按照注解进行过滤。
  • ASSIGNABLE_TYPE:按照给定的类型进行过滤。
  • ASPECTJ:按照ASPECTJ表达式进行过滤。
  • REGEX:按照正则表达式进行过滤。
  • CUSTOM:按照自定义规则进行过滤,使用自定义过滤规则时,自定义的过滤器需要实现org.springframework.core.type.filter.TypeFilter接口。

在FilterType枚举类中,ANNOTATION和ASSIGNABLE_TYPE是比较常用的,ASPECTJ和REGEX不太常用,如果FilterType枚举类中的类型无法满足日常开发需求时,可以通过实现org.springframework.core.type.filter.TypeFilter接口来自定义过滤规则,此时,将@Filter中的type属性设置为FilterType.CUSTOM,classes属性设置为自定义规则的类对应的Class对象。

三、使用案例

用Spring的注解开发应用程序时,如果需要将标注了Spring注解的类注入到IOC容器中,就需要使用@ComponentScan注解来扫描指定包下的类。同时,在Spring4.3版本开始,提供了@ComponentScans注解,在@ComponentScans注解中,支持配置多个@ComponentScan注解来扫描不同的包,配置不同的过滤规则。

1. 案例描述

使用自定义过滤规则实现Spring扫描指定包下的类时,使得名称中含有 componentScanConfig 字符串的类符合过滤规则。

2. 案例实现

整个案例实现的步骤总体如下所示。

(1)新建自定义过滤规则类ComponentScanFilter

public class ComponentScanFilter implements TypeFilter {
	/**
	 * 此方法返回一个boolean类型的值。
	 * 当返回true时,表示加入到spring的容器中。返回false时,不加入容器。
	 * 参数metadataReader:表示读取到的当前正在扫描的类的信息
	 * 参数metadataReaderFactory:表示可以获得到其他任何类的信息
	 */
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        //获取当前正在扫描的类的信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        //获取当前正在扫描的类名
        String className = classMetadata.getClassName();
        return className.contains("componentScanConfig");
    }
}

可以看到,自定义过滤规则ComponentScanFilter类实现了TypeFilter接口,并覆写了match()方法,match()方法中的核心逻辑就是:如果类的名称中含有componentScanConfig字符串,符合过滤规则,返回true,否则,返回false。

(2)新建配置类ComponentScanConfig

@Configuration
@ComponentScan(value = "com.lwk.demo.spring.annocation", includeFilters = {
    @Filter(type = FilterType.CUSTOM, classes = {ComponentScanFilter.class})
}, useDefaultFilters = false)
public class ComponentScanConfig {
}

可以看到,在ComponentScanConfig类上标注了@Configuration注解,说明ComponentScanConfig类是Spring的配置类。在标注的@ComponentScan注解中指定了要扫描的包名,使用只包含的过滤规则,并采用自定义过滤规则。

此时,需要注意的是,需要将是否使用默认的过滤规则设置为false。

(3)新建测试类ComponentScanTest

public class ComponentScanTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ComponentScanConfig.class);
        String[] names = context.getBeanDefinitionNames();
        Arrays.stream(names).forEach(System.out::println);
    }
}

可以看到,在ComponentScanTest类中,在AnnotationConfigApplicationContext类的构造方法中传入ComponentScanConfig类的Class对象创建IOC容器,并将其赋值给context局部变量。通过context局部变量的getBeanDefinitionNames()方法获取所有的Bean定义名称,随后遍历这些Bean定义名称进行打印。

3. 案例测试

本案例中,在@ComponentScan注解中使用了includeFilters过滤规则,并且使用的是自定义过滤规则,符合过滤规则的是名称中含有 componentScanConfig 字符串的类。另外,Spring中内置的Processor类和Factory类的Bean定义信息注册到IOC容器时,不受过滤规则限制。

运行ComponentScanTest类输出的结果信息如下所示:

11:14:21.476 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@41975e01
11:14:21.504 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
11:14:21.691 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
11:14:21.694 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
11:14:21.696 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
11:14:21.698 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
11:14:21.711 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'componentScanConfig'
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
componentScanConfig

可以看到,从IOC容器中获取的Bean的类定义信息的名称中可以看出,除了名称中包含componentScanConfig字符串的类符合过滤规则外,Spring内置的Processor类和Factory类不受过滤规则限制,其类的Bean定义信息都注册到了IOC容器中。

4. 其他应用案例

(1)扫描时排除注解标注的类

排除@Controller、@Service和@Repository注解,可以在配置类上通过@ComponentScan注解的excludeFilters()属性实现,如下所示:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", excludeFilters = {
    @Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class, Repository.class})
})

(2)扫描时只包含注解标注的类

可以使用ComponentScan注解类的includeFilters()属性来指定Spring在进行包扫描时,只包含哪些注解标注的类。如果使用includeFilters()属性来指定只包含哪些注解标注的类时,需要禁用默认的过滤规则。

例如,只包含@Controller注解标注的类,可以在配置类上添加@ComponentScan注解,设置只包含@Controller注解标注的类,并禁用默认的过滤规则,如下所示:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
}, useDefaultFilters = false)

(3)重复注解

在Java8中@ComponentScan注解是一个重复注解,可以在一个配置类上重复使用这个注解,如下所示:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
}, useDefaultFilters = false)
@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.ANNOTATION, classes = {Service.class})
}, useDefaultFilters = false)

如果使用的是Java8之前的版本,就不能直接在配置类上写多个@ComponentScan注解了。此时,可以在配置类上使用@ComponentScans注解,如下所示:

@ComponentScans(value = {
    @ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
        @Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
    }, useDefaultFilters = false),
    @ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
        @Filter(type = FilterType.ANNOTATION, classes = {Service.class})
    }, useDefaultFilters = false)
})

总结:可以使用@ComponentScan注解来指定Spring扫描哪些包,可以使用excludeFilters()指定扫描时排除哪些组件,也可以使用includeFilters()指定扫描时只包含哪些组件。当使用includeFilters()指定只包含哪些组件时,需要禁用默认的过滤规则。

(4)扫描时按照指定的类型进行过滤

使用@ComponentScan注解进行包扫描时,按照给定的类型只包含DemoService类(接口)或其子类(实现类或子接口)的组件,如下所示:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {DemoService.class})
}, useDefaultFilters = false)

此时,只要是DemoService类型的组件,都会被加载到容器中。也就是说:当DemoService是一个Java类时,DemoService类及其子类都会被加载到Spring容器中;当DemoService是一个接口时,其子接口或实现类都会被加载到Spring容器中。

(5)扫描时按照ASPECTJ表达式进行过滤

使用@ComponentScan注解进行包扫描时,按照ASPECTJ表达式进行过滤,如下所示:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.ASPECTJ, classes = {AspectJTypeFilter.class})
}, useDefaultFilters = false)

其中,AspectJTypeFilter类就是自定义的ASPECTJ表达式的过滤器类。

(6)扫描时按照正则表达式进行过滤

使用@ComponentScan注解进行包扫描时,按照正则表达式进行过滤,如下所示:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.REGEX, classes = {RegexPatternTypeFilter.class})
}, useDefaultFilters = false)

其中,RegexPatternTypeFilter类就是自定义的正则表达式的过滤器类。

(7)扫描时按照自定义规则进行过滤

如果实现自定义规则进行过滤时,自定义规则的类必须是org.springframework.core.type.filter.TypeFilter接口的实现类。

例如,按照自定义规则进行过滤,首先,需要创建一个org.springframework.core.type.filter.TypeFilter接口的实现类BingheTypeFilter,如下所示:

public class BingheTypeFilter implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        return false;
    }
}

当实现TypeFilter接口时,需要实现TypeFilter接口中的match()方法,match()方法的返回值为boolean类型。当返回true时,表示符合过滤规则,会将类的Bean定义信息注册到IOC容器中;当返回false时,表示不符合过滤规则,对应的类的Bean定义信息不会注册到IOC容器中。

接下来,使用@ComponentScan注解进行如下配置:

@ComponentScan(value = "io.binghe.spring.annotation.chapter02", includeFilters = {
    @Filter(type = FilterType.CUSTOM, classes = {BingheTypeFilter.class})
}, useDefaultFilters = false)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@MapperScan和@ComponentScan都是用来扫描包的注解,但是它们有着不同的功能和使用场景。 @MapperScan注解主要用于扫描mapper类,它会自动将这些类注册到MyBatis中,不需要在每个mapper类上加@MapperScan注解。这个注解通常用于与MyBatis框架一起使用,方便自动扫描mapper类并进行相关配置。 @ComponentScan注解是一个组件扫描注解,用于扫描标有特定注解(如@Controller、@Service、@Repository等)的类,并将它们装配到Spring容器中。这样,Spring容器就能自动识别并管理这些被扫描到的组件类。@ComponentScan注解可以指定扫描的路径,从中找出需要装配的类,并将其注入到Spring容器中。 所以,@MapperScan主要用于扫描mapper类,而@ComponentScan主要用于扫描带有特定注解的组件类。这两个注解的区别在于扫描的对象和使用的框架不同,@MapperScan用于MyBatis框架,而@ComponentScan用于Spring框架。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [@MapperScan和@ComponentScan的区别](https://blog.csdn.net/m0_37597572/article/details/82625631)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值