spring 按照规则排除不需要扫描的注解

spring通过@ComponentScan注解来指定扫描的范围。其中可通过 excludeFilters来指定哪些范围可以被排除在外。当type = FilterType.CUSTOM时,我们可以通过自定义代码的方式来灵活判断哪些类不用来示例化。

具体实现过程如下:

  1. 在配置类或启动类上加上如下注解
#type = FilterType.CUSTOM 代表自定义类型;classes = CustomFilterType.class自定义的扫描规则判断实现类。
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM,classes = CustomTypeFilter.class)})
  1. 实现自定义判断规则
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;

public class CustomTypeFilter implements TypeFilter {

    /**
     * 对于excludeFilters功能来说,返回值为true表示需要被排除在外,返回值为false表示不需要排除在外
     * 对于includeFilters功能与excludeFilters相反
     * @param metadataReader
     * @param metadataReaderFactory
     * @return
     * @throws IOException
     */
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        String className = metadataReader.getClassMetadata().getClassName();
       //todo:自定义处理逻辑
        if (className.equals("XXX")){
            return true;
        }
        return false;
    }
}
如果还有其他使用需求,详细情况可以参考@ComponentScan.Filter的使用说明。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用注解配置Spring应用程序时,我们需要使用`@ComponentScan`注解来指定Spring容器扫描的包路径。`@ComponentScan`注解可以放在任何一个Java配置类上,用于告诉Spring应该扫描哪些包来查找组件。 具体来说,`@ComponentScan`注解有以下几个常用属性: - `basePackage`:指定一个或多个要扫描的包路径。例如`@ComponentScan(basePackage = "com.example")`会扫描`com.example`包及其子包中的所有类,并将其加入到Spring容器中。 - `basePackages`:与`basePackage`属性类似,可以指定多个要扫描的包路径,例如`@ComponentScan(basePackages = {"com.example.service","com.example.dao"})`会扫描`com.example.service`和`com.example.dao`包中的所有类。 - `includeFilters`:指定一个或多个`@ComponentScan.Filter`类型的过滤器,用于从扫描结果中筛选出需要包含的组件。 - `excludeFilters`:指定一个或多个`@ComponentScan.Filter`类型的过滤器,用于从扫描结果中筛选出需要排除的组件。 例如,以下配置会告诉Spring扫描`com.example`包及其子包中所有使用`@Component`、`@Controller`、`@Service`和`@Repository`注解的类,并将其加入到Spring容器中: ```java @Configuration @ComponentScan(basePackages = "com.example", includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Component.class, Controller.class, Service.class, Repository.class})}) public class AppConfig { // ... } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值