zoukankan      html  css  js  c++  java
  • 【spring】之基于注解@ComponentScan的一些使用

    基于xml形式ComponentScan的使用如下

    <context:component-scan base-package="com.luna" use-default-filters="false">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    基于注解@ComponentScan的使用

    @Configuration

    /*@ComponentScan(value = "com.luna", includeFilters = {

       // @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
       // @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value ={com.luna.service.PersonService.class} )
       @ComponentScan.Filter(type = FilterType.CUSTOM,value = {MyFilter.class})
     },useDefaultFilters = false)*/

    @ComponentScan(value = "com.luna"

        //排除某些类
        excludeFilters = { //排除Controller注解标注的类
        @ComponentScan.Filter(type
    = FilterType.ANNOTATION, classes = {Controller.class}),
    //排除指定类型的类 @ComponentScan.Filter(type
    = FilterType.ASSIGNABLE_TYPE,value ={com.luna.service.PersonService.class} ) }) public class ScanConfig { }

    测试

    @Test
        public void test(){
            AnnotationConfigApplicationContext applicationContext = 
                    new AnnotationConfigApplicationContext(ScanConfig.class);
            String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
            Arrays.asList(beanDefinitionNames).stream().forEach(x->System.out.println("扫描到的Bean---"+x));
        }

    @ComponentScan一些常用参数

    //基本属性 value/basePackages:指定一组要扫描的包,将扫描这些包及其子包下的文件.(默认基包为配置类所在的包)

    classes:直接指定扫描的一些类,这些类所在的包及其子包也会被扫描。

    nameGenerator:指定一个默认扫描组件的命名类, 默认命名使用组件类名第一个字小写。

    excludeFilters:指定扫描的时候排除某些类,按什么规则,需要一组@ComponentScan.Filter的注解配置,每个@Filter可以配置一组过滤规则,多个@Filter可以基于正则/注解/具体类配置不同的过滤规则。

    includeFilters:指定扫描的时候,只包含某些类。

    useDefaultFilters 自动扫描Controller Component Service Resposity 这四个注解
    所以在不指定明确包的情况下如 com.luna 全包扫描,会扫描到Controller Component Service Resposity 四个注解

    FilterType.ANNOTATION(默认) 一组注解,命中所有使用该注解的类,{MyAnno.class} -
    FilterType.ASSIGNABLE_TYPE 一组具体类 -
    FilterType.ASPECTJ - 一组表达式,使用Aspectj表达式命中类
    FilterType.REGEX - 一组表达式,使用正则命中类
    FilterType.CUSTOM 自定义的TypeFilter. -
  • 相关阅读:
    多进程之数据安全问题
    windows 下安装 RabbitMQ
    springCloud Config分布式配置中心
    git配置ssh
    spring cloud Gateway 新一代网关
    spring cloud Hystrix 断路器
    spring cloud OpenFeign 服务接口调用
    Ribbon负载均衡服务调用
    consul服务注册与发现
    Eureka服务治理
  • 原文地址:https://www.cnblogs.com/gyjx2016/p/8903753.html
Copyright © 2011-2022 走看看