iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring@ComponentScan注解使用案例详细讲解
  • 545
分享到

Spring@ComponentScan注解使用案例详细讲解

Python 官方文档:入门教程 => 点击学习

摘要

目录一、简单介绍二、注解说明1. @ComponentScans注解源码2. @ComponentScan注解源码3. ScopedProxyMode枚举类源码4. FilterTy

一、简单介绍

翻开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)
@Documented
public @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类输出的结果信息如下所示:

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

扫描时排除注解标注的类

排除@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注解使用案例详细讲解的文章就介绍到这了,更多相关Spring @ComponentScan注解内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring@ComponentScan注解使用案例详细讲解

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

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

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

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

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作