小编典典

使用spring.profiles.include包含配置文件似乎会覆盖而不是包含

spring-boot

我正在尝试对几个Spring Boot应用程序的配置属性进行分区。我使用的是Spring Boot
1.1.6,我们的配置属性以YAML的常规application.yml样式表示。我已经为常用的基本参数,常用的数据库参数等创建了各种配置文件。我试图使用Spring
Boot参考文档中提到的include功能,但它似乎是一个替代而不是include。即与我想要的完全相反。给定application.yml中的以下内容,我希望当
bar* 配置文件处于活动状态时属性 名称 具有值 bar ,但实际上将其设置为 foo
***(来自随附的配置文件)。
我认为include的概念意味着它首先被加载,并且在新配置文件中设置的任何名称相同的属性都将覆盖包含的配置文件中的那些属性。有点像子类正在遮罩超类中的字段,子类的任何实例都会反映出遮蔽的值。这是文件:

spring:
  profiles: foo
name: foo

--- # New YAML doc starts here

spring:
  profiles: 
    include: foo
  profiles: bar
name: bar

如果我在显式激活“ bar”配置文件的测试用例中运行此文件,则 name 属性仍为foo:

SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
SpringApplication app = builder.application();
builder.profiles("bar");
ConfigurableApplicationContext ctxt = app.run();
String name = ctxt.getEnvironment().getProperty("name"); // Is always "foo" much to my surprise

但是,如果我注释掉包括:

spring: 
profiles: bar
#  profiles: 
#    include: foo

并在我的代码中显式激活两个配置文件:

builder.profiles("foo", "bar");

然后,它按我期望的方式工作,并且 name 属性设置为 bar
。我宁愿处理YAML文件中的包含的主要原因是,它对我的​​实际代码的影响较小,并且我可以在一个地方管理所有配置文件包含。使用另一种方法,如果要重命名配置文件,则必须在整个项目中搜索配置文件字符串和可能的@Profile注释。绝对更容易出错。我认为更灵活的解决方案是显式地表达所包含的配置文件是否覆盖子配置文件值。也许像:

spring:
  profiles: bar
  profiles:
    include: foo
      override: false

也许我只是在这里想念东西。有更好的方法吗?谢谢。


阅读 5687

收藏
2020-05-30

共1个答案

小编典典

尝试以下操作以将 foo 包括在内,但覆盖 bar ,似乎对我的解决方案有效

spring:
    profiles:
        include: bar
        active: foo,bar

编辑: 请记住,这是一个“ hack”,未得到正式支持,适用于2016版

2020-05-30