SpringBoot—@ComponentScan注解過濾排除某個類的三種方法
一、引言
在引用jar包的依賴同時,經(jīng)常遇到有包引用沖突問題。一般我們的做法是在Pom文件中的dependency節(jié)點下添加exclusions配置,排除特定的包。
這樣按照包做的排除范圍是比較大的,現(xiàn)在我們想只排除掉某個特定的類,這時我們怎么操作呢?文章來源:http://www.zghlxwxcb.cn/news/detail-607054.html
二、解決沖突的方法
方法一: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);
}
}
- 優(yōu)點:使用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);
}
}
- 優(yōu)點:可以通過正則去匹配目標類型的完全限定名,一個表達式可以過濾很多對象;
三、總結(jié)
不同場景下按需配置即可,我遇到的問題是有那么幾十個類有沖突,不想注入這些類,這時我使用正則過濾特定類的方法解決了我的問題。文章來源地址http://www.zghlxwxcb.cn/news/detail-607054.html
到了這里,關(guān)于SpringBoot—@ComponentScan注解過濾排除不加載某個類的三種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!