用于配置文件组合的Spring Boot YAML配置

时间:2019-06-04 09:51:25

标签: java spring spring-boot configuration

documentation的Spring引导YAML配置中:

  

如果YAML文档包含一个spring.profiles键,则配置文件值(以逗号分隔的配置文件列表)将被馈送到Spring Environment.acceptsProfiles()方法中。如果这些配置文件中的任何一个处于活动状态,则该文档将包含在最终合并中...

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

我想要的是AND逻辑。我有多种机器类型和区域,我想在机器类型和区域的特定组合上启用一些配置,例如production,Europe

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

2 个答案:

答案 0 :(得分:0)

我认为这更适合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.
        }
    }
}

或者,您可以创建自己的@ConfigurationPropertieshttps://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。

答案 1 :(得分:0)

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

spring:
  profiles:
    active: "production,Europe"

---

spring:
  profiles: production

one: prd one
two: prd two
three: prd three

---

spring:
  profiles: Europe

one: EU one
four: EU four


会给你

one: EU one  // <------
two: prd two
three: prd three
four: EU four

但是如果您反转订单(有效:“欧洲,生产”)

你得到

one: prd one    // <------
two: prd two
three: prd three
four: EU four