前言
需求很简单,我不想在idea新建个项目,但是功能同样的类,我需要多份,但是还不想改变名称,原因是太多。我就想新建个包,把他们复制过去,改改配置。但是不改类名,容器扫描会有冲突(除非给其加上别名),因为我的包名和环境名相同,如果能根据环境的不同,容器扫描不同的类最好不过。
需求解决
需求修改对ComponentScan的配置
@ComponentScan(
value = "com.delicacy",
excludeFilters = {@ComponentScan.Filter(
type = FilterType.CUSTOM,
classes = {ExcludeScanPackagesFilter.class}
)}
)
如果环境是如下:
application-dev-aa.yml
application-dev-bb.yml
application-dev-cc.yml
包名如下:
com.xxx.aa
com.xxx.bb
com.xxx.cc
public class ExcludeScanPackagesFilter implements TypeFilter, EnvironmentAware {
private List<String> excludePackages;
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
String[] var1 = classMetadata.getClassName().split("\\.");
List<String> var2 = Arrays.asList(var1);
if (var2.stream().anyMatch(e -> excludePackages.contains(e))) {
log.info("排除的类的类名{}", classMetadata.getClassName());
return true;
}
return false;
}
@Override
public void setEnvironment(Environment environment) {
String[] activeProfiles = environment.getActiveProfiles();
String scanPackage = "";
if (activeProfiles.length > 0) {
String activeProfile = activeProfiles[0];
scanPackage = activeProfile.split("-")[1];
}
switch (scanPackage) {
case "aa": {
this.excludePackages = Arrays.asList("bb", "cc");
return;
}
default:
this.excludePackages = Arrays.asList("aa", "bb", "cc");
}
}
}