相关疑难解决方法(0)

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

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

spring:
  profiles: foo
name: foo

--- # New YAML doc starts here

spring:
  profiles: 
    include: foo
  profiles: bar
name: bar
Run Code Online (Sandbox Code Playgroud)

如果我在显式激活"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
Run Code Online (Sandbox Code Playgroud)

但是,如果我评论出包括:

spring: 
profiles: bar
#  profiles: 
#    include: foo
Run Code Online (Sandbox Code Playgroud)

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

builder.profiles("foo", "bar");
Run Code Online (Sandbox Code Playgroud)

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

spring: …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot

16
推荐指数
1
解决办法
1万
查看次数

标签 统计

spring ×1

spring-boot ×1