SpringBoot中@ComponentScan注解过滤排除不加载某个类的3种方法
作者:草青工作室
这篇文章主要给大家介绍了关于SpringBoot中@ComponentScan注解过滤排除不加载某个类的3种方法,文中通过实例代码介绍的非常详细,对大家学习或者使用SpringBoot具有一定的参考学习价值,需要的朋友可以参考下
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);
}
}优点:可以通过正则去匹配目标类型的完全限定名,一个表达式可以过滤很多对象;
三、总结
不同场景下按需配置即可,我遇到的问题是有那么几十个类有冲突,不想注入这些类,这时我使用正则过滤特定类的方法解决了我的问题。
到此这篇关于SpringBoot中@ComponentScan注解过滤排除不加载某个类的3种方法的文章就介绍到这了,更多相关@ComponentScan注解过滤排除某个类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
