0


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

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

一、引言

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

二、解决冲突的方法

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

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
    <exclusions>
            <exclusion>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId>
            </exclusion>
    </exclusions>
    </dependency>
  • 缺点:排除的范围比较大,不能排除指定对象;

方法二:@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);
    }
}
  • 优点:使用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);
    }
}
  • 优点:可以通过正则去匹配目标类型的完全限定名,一个表达式可以过滤很多对象;

三、总结

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

标签: spring boot java 后端

本文转载自: https://blog.csdn.net/xxj_jing/article/details/128101592
版权归原作者 草青工作室 所有, 如有侵权,请联系我们删除。

“SpringBoot—@ComponentScan注解过滤排除不加载某个类的三种方法”的评论:

还没有评论