iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Spring @ComponentScan注解如何使用
  • 742
分享到

Spring @ComponentScan注解如何使用

2023-07-05 11:07:21 742人浏览 薄情痞子
摘要

今天小编给大家分享一下spring @ComponentScan注解如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解

今天小编给大家分享一下spring @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注解源码

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Documentedpublic @interface ComponentScans { ComponentScan[] value();}

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

2. @ComponentScan注解源码

@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对象。

  • nameGenerator:Class<? extends BeanNameGenerator>类型,指定扫描类时,向IOC注入Bean对象时的命名规则。

  • scopeResolver:Class<? extends ScopeMetadataResolver>类型,扫描类时,用于处理并转换符合条件的Bean的作用范围。

  • scopedProxy:ScopedProxyMode类型,指定生成Bean对象时的代理方式,默认的代理方法是DEFAULT,也就是不使用代理。关于ScopedProxyMode的更多详细的内容,参见后面章节。

  • resourcePattern:String类型,用于指定扫描的文件类型,默认是扫描指定包下的**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扫描类时的过滤类型

    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. 案例实现

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

    新建自定义过滤规则类ComponentScanFilter
    public class ComponentScanFilter implements TypeFilter {    @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。

    新建配置类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。

    新建测试类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类输出的结果信息如下所示:

    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. 其他应用案例

    扫描时排除注解标注的类

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

    @ComponentScan(value = "io.binghe.spring.annotation.chapter02", excludeFilters = {    @Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class, Repository.class})})
    扫描时只包含注解标注的类

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

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

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

    在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()指定只包含哪些组件时,需要禁用默认的过滤规则。

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

    使用@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容器中。

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

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

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

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

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

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

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

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

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

    如果实现自定义规则进行过滤时,自定义规则的类必须是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)

    以上就是“Spring @ComponentScan注解如何使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网精选频道。

--结束END--

本文标题: Spring @ComponentScan注解如何使用

本文链接: https://www.lsjlt.com/news/351280.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring @ComponentScan注解如何使用
    今天小编给大家分享一下Spring @ComponentScan注解如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解...
    99+
    2023-07-05
  • Spring@ComponentScan注解使用案例详细讲解
    目录一、简单介绍二、注解说明1. @ComponentScans注解源码2. @ComponentScan注解源码3. ScopedProxyMode枚举类源码4. FilterTy...
    99+
    2023-03-10
    Spring @ComponentScan注解 Spring @ComponentScan Spring @ComponentScan扫描组件
  • 基于@ComponentScan注解的使用详解
    目录@ComponentScan注解的使用一、注解定义二、使用1.环境准备2.excludeFilters的使用3.includeFilters的使用4.自定义过滤规则关于@Comp...
    99+
    2024-04-02
  • spring boot自动装配之@ComponentScan注解用法详解
    目录1.@ComponentScan注解作用2. @ComponentScan注解属性3. @ComponentScan过滤规则说明4. 自定义扫描过滤规则5. @Component...
    99+
    2023-05-18
    @componentscan注解 @componentscan注解用法 componentscan作用
  • Spring@ComponentScan注解扫描组件原理
    目录ConfigurationClassPostProcessor类Parse each @Configuration classComponentScanAnnotationPar...
    99+
    2023-01-10
    Spring @ComponentScan注解 Spring @ComponentScan Spring @ComponentScan扫描组件
  • 详解Spring系列之@ComponentScan批量注册bean
    目录回顾本文内容@ComponentScan基本原理和使用基本原理使用案例定义组件定义配置类容器扫描和使用@ComponentScan进阶使用源码简析案例1:使用Filters过滤案...
    99+
    2024-04-02
  • Spring @InitBinder注解如何使用
    这篇文章主要讲解了“Spring @InitBinder注解如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring @InitBinder注解如何使用”吧!一...
    99+
    2023-07-05
  • Spring @Profile注解如何使用
    这篇文章主要介绍“Spring @Profile注解如何使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring @Profile注解如何使用”文章能帮助大家解决问题。使用...
    99+
    2023-07-06
  • Spring component-scan XML配置与@ComponentScan注解配置
    目录前言准备@Component的beanXML配置Java配置 配置@Configuration的beanXML配置 配置Java配置 配置小结总结关于SpringBoot前言 无...
    99+
    2024-04-02
  • 如何使用注解开发spring
    本篇文章为大家展示了如何使用注解开发spring,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。在Spring4之后,要使用注解开发,必须要保证aop的包导入了。使用注解需要导入context约束,增...
    99+
    2023-06-15
  • Java中如何使用Spring注解
    Java中如何使用Spring注解,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。在Spring4之后,要使用注解开发,必须要保证aop的包导入了使用注解需要导入contex...
    99+
    2023-06-20
  • Spring中@ModelAttribute注解如何使用
    这期内容当中小编将会给大家带来有关Spring中@ModelAttribute注解如何使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1.@ModelAttribute注释方法   例子(1)...
    99+
    2023-06-02
  • spring中如何使用@Service注解
    本篇文章为大家展示了spring中如何使用@Service注解,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。@Service注解的使用要说明@Service注解的使用,就得说一下我们经常在sprin...
    99+
    2023-06-20
  • 详解spring如何使用注解开发
    在Spring4之后,要使用注解开发,必须要保证aop的包导入了。 使用注解需要导入context约束,增加注解的支持。 <?xml version="1.0" ...
    99+
    2024-04-02
  • 如何在Spring中使用@Transactional注解
    这期内容当中小编将会给大家带来有关如何在Spring中使用@Transactional注解,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。@Transactionalservice A(){try...
    99+
    2023-06-15
  • @profile注解如何在spring中使用
    本篇文章给大家分享的是有关@profile注解如何在spring中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。首先是新建maven工程mvn archetype:gene...
    99+
    2023-05-30
    spring profile
  • 使用Spring MVC4 如何配置注解
    使用Spring MVC4 如何配置注解?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。在传统的Spring项目中,我们要写一堆的XML文件。而这些XML文件格式...
    99+
    2023-05-31
    springmvc 注解配置
  • 如何使用注解配置Spring容器
    这篇文章给大家分享的是有关如何使用注解配置Spring容器的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。具体如下:@Configuration标注在类上,相当于将该类作为spring的xml的标签@Configu...
    99+
    2023-05-30
    spring
  • 使用Spring Aop如何配置AspectJ注解
    这篇文章将为大家详细讲解有关使用Spring Aop如何配置AspectJ注解,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。采用的jdk代理,接口和实现类代码请参考上篇博文。主要是将Aspe...
    99+
    2023-05-31
    springaop aspectj
  • Spring注解@Configuration与@Bean注册组件如何使用
    今天小编给大家分享一下Spring注解@Configuration与@Bean注册组件如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一...
    99+
    2023-07-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作