springboot @ComponentScan排除指定類
因為A工程依賴於B工程,B工程為某些通用模組的工程,含有controller、service等通用業務。這時A專案會配置@ComponentScan掃碼B工程的包,由於某種原因需要排除某些被@Service標註的類,不將他們加入spring容器中,於是就用上了@ComponentScan的excludeFilters屬性。
使用方法
excludeFilters屬性需要傳遞@ComponentScan.Filter註解
該註解需指定FilterType,FilterType共有下面5種選擇:
-
ANNOTATION
篩選含有某個註解的,例如
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {ExcludeComponent.class}))
其中ExcludeComponent是我個人指定的註解可以自己建,只要有該註解標註就會被排除。 -
ASSIGNABLE_TYPE 篩選指定型別的
-
ASPECTJ 篩選匹配給定AspectJ型別模式表示式的
-
REGEX 篩選正則表示式匹配的
-
CUSTOM 自定義篩選
自定義
自定義規則需繼承org.springframework.core.type.filter.TypeFilter類,實現match方法即可。例如:
public class CustomFilter implements TypeFilter { private static final String PACKAGE = ".aaa."; @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { // 可以通過MetadataReader獲得各種資訊,然後根據自己的需求返回boolean,例項表示包名含有aaa路徑的類名將滿足篩選條件。 return metadataReader.getClassMetadata().getClassName().contains(PACKAGE); } }
配置
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, classes = CustomFilter.class))
結果就是含有aaa路徑的類名將被排除不被加入spring容器中。
注意事項
如果工程中存在多個@ComponentScan,需要都進行excludeFilters配置否排除會失效!!!