在我的应用程序中,我有两个配置文件dev
和prod
,我可以使用org.springframework.context.annotation.Profile
注释排除 bean:
package com.example.prod;
@Service
@Profile("prod")
public class MyService implements MyBaseService {}
问题是,我有几个以这种方式注释的豆子,它们都在同一个包com.example.prod
中。dev
配置文件(com.example.dev
包)也存在类似的结构,将来我可能会有一些额外的配置文件。是否可以一次排除整个包裹?我尝试玩org.springframework.context.annotation.ComponentScan
,但我无法根据实际配置文件添加排除过滤器,我想知道是否有简单的方法来解决我的问题。
您可以实现自定义类型过滤器,以根据活动配置文件禁用某些包的ComponentScan
。一个启动的例子是:
(1) 实现过滤器。出于演示目的,我硬编码如果活动配置文件dev
,它将排除由devExcludePackage
属性配置的包。对于prod
配置文件,它将排除由prodExcludePackage
配置的软件包:
public class ExcludePackageTypeFilter implements TypeFilter , EnvironmentAware {
private Environment env;
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
boolean match = false;
for (String activeProfile : env.getActiveProfiles()) {
if (activeProfile.equals("dev")) {
match = isClassInPackage(metadataReader.getClassMetadata(), env.getProperty("devExcludePackage"));
} else if (activeProfile.equals("prod")) {
match = isClassInPackage(metadataReader.getClassMetadata(), env.getProperty("prodExcludePackage"));
}
}
return match;
}
private boolean isClassInPackage(ClassMetadata classMetadata, String pacakage) {
return classMetadata.getClassName().startsWith(pacakage);
}
@Override
public void setEnvironment(Environment environment) {
this.env = environment;
}
}
(2) 配置application.properties
以定义要为不同配置文件排除的包。
devExcludePackage = com.example.prod
prodExcludePackage = com.example.dev
(3) 将此过滤器应用于@ComponentScan
:
@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(
type = FilterType.CUSTOM, classes = { ExcludePackageTypeFilter.class }))
public class Application {
}