• SpringBoot—@ComponentScan注解过滤排除不加载某个类的三种方法


    SpringBoot—@ComponentScan注解过滤排除某个类的三种方法

    一、引言

    在引用jar包的依赖同时,经常遇到有包引用冲突问题。一般我们的做法是在Pom文件中的dependency节点下添加exclusions配置,排除特定的包。
    这样按照包做的排除范围是比较大的,现在我们想只排除掉某个特定的类,这时我们怎么操作呢?

    二、解决冲突的方法

    方法一:pom中配置排除特定包

    
        org.slf4j
        slf4j-log4j12
        ${slf4j.version}
        
                
                slf4j-api
                org.slf4j
                
        
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 缺点:排除的范围比较大,不能排除指定对象;

    方法二:@ComponentScan过滤特定类

    @ComponentScan(value = "com.xxx",excludeFilters = {
    		@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {
    				com.xxx.xxx.xxx.class,
    				com.xxx.xxx.xxx.class,
                    ....
    		})
    })
    @SpringBootApplication
    public class StartApplication {
    	public static ApplicationContext applicationContext = null;
    	public static void main(String[] args) {
    		applicationContext = SpringApplication.run(StartApplication.class, args);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 优点:使用FilterType.ASSIGNABLE_TYPE配置,可以精确的排除掉特定类的加载和注入;
    • 缺点:如果有很多类需要排除的话,这种写法就比较臃肿了;

    方法三:@ComponentScan.Filter使用正则过滤特定类

    @ComponentScan(value = "com.xxx",excludeFilters = {
    	@ComponentScan.Filter(type = FilterType.REGEX,pattern = {
                //以下写正则表达式,需要对目标类的完全限定名完全匹配,否则不生效
    			"com.xxx.xxx.impl.service.+",
                ....
    	})
    })
    @SpringBootApplication
    public class StartApplication {
    	public static ApplicationContext applicationContext = null;
    	public static void main(String[] args) {
    		applicationContext = SpringApplication.run(StartApplication.class, args);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 优点:可以通过正则去匹配目标类型的完全限定名,一个表达式可以过滤很多对象;

    三、总结

    不同场景下按需配置即可,我遇到的问题是有那么几十个类有冲突,不想注入这些类,这时我使用正则过滤特定类的方法解决了我的问题。

  • 相关阅读:
    [python]用flask框架搭建微信公众号的后台
    深度学习进度显示神器:tqdm详解
    form onSubmit返回false不起作用
    Java的指针、引用与C++的指针、引用的对比
    8月《中国数据库行业分析报告》已发布,聚焦数据仓库、首发【全球数据仓库产业图谱】
    线上故障突突突?如何紧急诊断、排查与恢复
    MySQL 数据库 查询定义参数【模糊查询】
    docker删除镜像
    Redis主从结构数据同步分析
    python实操题二(含答案)
  • 原文地址:https://blog.csdn.net/xxj_jing/article/details/128101592