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

标签 java spring spring-boot configuration

来自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/

相关文章:

java - Spring @scheduled 带有 cron 但没有重叠的 cron

spring-boot - Spring安全错误: java. lang.IllegalStateException:无法在其自身之后配置anyRequest

java - json 路径表达式来查找与特定名称对应的值

java - 构建时错误 : content is not allowed in prolog

spring - 当作为另一个依赖项添加到另一个 Spring Boot 应用程序时,使用 @Scheduled 注释的方法在 Spring Boot 应用程序中不起作用

java - Jackson 和 Jersey 的条件属性序列化

java - Spring Boot UnsatisfiedDependencyException 创建名称为不可解析循环引用的 bean 时出错

java - 重试队列绑定(bind)到 RabbitMQ 交换

java - 将 2D ArrayList<Double> 转换为 double 的 2D 数组

java - Junit参数化测试,不一样的想法