gpt4 book ai didi

java - 用于配置文件组合的 Spring boot YAML 配置

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:32 25 4
gpt4 key购买 nike

来自documentation在 Spring 启动 YAML 配置上:

If a YAML document contains a spring.profiles key, then the profiles value (a comma-separated list of profiles) is fed into the Spring Environment.acceptsProfiles() method. If any of those profiles is active, that document is included in the final merge...

因此 spring.profiles 键具有 OR 逻辑。如果将其设置为 test,dev,则当 Spring 配置文件包含 test 或 dev 时,将应用该配置。

我想要的是AND逻辑。我有多种机器类型和区域,并且我想在机器类型和区域的特定组合上启用某些配置,例如生产,欧洲

是否可以根据 YAML 文件中的配置文件组合来设置配置?

最佳答案

我相信这更适合 ApplicationListenerEnvironmentPostProcessor:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-boot-application.html#howto-customize-the-environment-or-application-context

例如,您的 AND 逻辑可能是:

@Component
public class MyListener {
@EventListener
public void handleContextStart(ApplicationPreparedEvent event) {
ConfigurableEnvironment env = event.getApplicationContext().getEnvironment();

if (env.acceptsProfiles(Profiles.of("test")) && env.acceptsProfiles(Profiles.of("test"))) {
// Do the AND configuration here.
}
}
}

或者,您可以创建自己的@ConfigurationProperties:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties

并在@PostConstruct方法中,进行进一步的自定义:

@ConfigurationProperties("myKey")
public class MyProperties implements EnvironmentAware {

private Environment Environment;
private MachineType machineType;
private String region;

@Override
public setEnvironment(Environment environment) {
this.environment = environment;
}

enum MachineType {
MAC_OS,
WINDOWS,
LINUX
}

@PostConstruct
void init() {
if (environment.acceptProfiles(Profiles.of("dev"))) {
// Do some work setting other properties
if (machineType == MachineType.WINDOWS) {
// some other work if it's Windows
}
}
}
}

然后在整个应用程序中使用 MyProperties bean。

关于java - 用于配置文件组合的 Spring boot YAML 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441487/

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