gpt4 book ai didi

java - 如何在 Spring Boot 应用程序中排除给定运行时配置文件中的包

转载 作者:行者123 更新时间:2023-11-30 01:56:21 27 4
gpt4 key购买 nike

在我的应用程序中,我有两个配置文件devprod,我可以使用org.springframework.context.annotation.Profile注释排除bean :

package com.example.prod;

@Service
@Profile("prod")
public class MyService implements MyBaseService {}

问题是,我有几个以这种方式注释的bean,它们都在同一个包com.example.prod中。 dev 配置文件(com.example.dev 包)也存在类似的结构,并且将来我可能会有一些额外的配置文件。是否有可能一次性排除整个包裹?我尝试使用 org.springframework.context.annotation.ComponentScan,但我无法根据实际配置文件添加排除过滤器,我想知道是否有简单的方法来解决我的问题。

最佳答案

您可以实现自定义 TypeFilter根据 Activity 配置文件禁用某些软件包的 ComponentScan 。一个启动示例是:

(1) 实现过滤器。出于演示目的,我硬编码了如果 Activity 配置文件是 dev ,它将排除由 devExcludePackage 属性配置的包。对于 prod profile ,它将排除 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 {


}

关于java - 如何在 Spring Boot 应用程序中排除给定运行时配置文件中的包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380979/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com