Spring 底层注解 - @CompentScan

本文详细介绍了@Configuration配合@ComponentScan注解在Spring框架中进行组件扫描的用法,包括如何排除(@ExcludeFilters)和包含(@IncludeFilters)特定类型的组件,并列举了FilterType的几种类型。同时,展示了自定义FilterType的实现方式,通过示例展示了如何根据类名包含特定字符串进行过滤。
摘要由CSDN通过智能技术生成

在配置类上写@CompentScan注解来进行包扫描.

@Configuration
@ComponentScan(basePackages = {"com.test.testcompentscan"})
public class MainConfig {
}

①: 排除用法 excludeFilters(排除@Controller注解的,和XxService的)

@Configuration
@ComponentScan(basePackages = {"com.test.testcompentscan"},excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {  XxService.class})
})
public class MainConfig {
}

②: 包含用法 includeFilters ,注意,若使用包含的用法, 需要把useDefaultFilters属性设置为 false(true表
示扫描全部的)

@Configuration
@ComponentScan(basePackages = {"com.test.testcompentscan"},includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})
},useDefaultFilters = false)
public class MainConfig {
}

③ @ComponentScan.Filter type的类型

a) 注解形式的FilterType.ANNOTATION @Controller @Service @Repository @Compent

b) 指定类型的 FilterType.ASSIGNABLETYPE @ComponentScan.Filter(type = FilterType.ASSIGNABLETYPE,value = {TulingService.class})

c) aspectj类型的 FilterType.ASPECTJ(不常用)

d) 正则表达式的 FilterType.REGEX(不常用)

e) 自定义的 FilterType.CUSTOM

public enum FilterType {
    //注解形式  比如@Controller @Service @Repository  @Compent
ANNOTATION,
    //指定的类型
ASSIGNABLE_TYPE,
    //aspectJ形式的
ASPECTJ,
    //正则表达式的
REGEX,
    //自定义的
CUSTOM
}

③ ①FilterType.CUSTOM 自定义类型如何使用

public class TestFilterType implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        //获取当前类的注解源信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        //获取当前类的class的源信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        //获取当前类的资源信息
        Resource resource =  metadataReader.getResource();
        if(classMetadata.getClassName().contains("dao")) {
            return true;
        }
        return false;
    }
}

@ComponentScan(basePackages = {"com.tuling.testcompentscan"},includeFilters = {
        @ComponentScan.Filter(type = FilterType.CUSTOM,value = TestFilterType .class)
},useDefaultFilters = false)
public class MainConfig {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半夏_2021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值