【问题标题】:setting spring configuration for multiple profile为多个配置文件设置弹簧配置
【发布时间】:2018-11-27 18:59:27
【问题描述】:

我的应用程序配置文件中有多个配置文件application.yml,如下例所示:

spring:
  application:
    name: my-super-app
database:
  secret: "default secret"
this:
  that: "default value..."

---

spring:
  profiles: staging


---

spring:
  profiles: qa
database:
  secret: "foo bar"

---

spring:
  profiles: playground
database:
  secret: "foo bar"

---

spring:
  profiles: production
database:
  secret: "foo bar"

很明显,我为qaplaygroundproduction 配置文件冗余设置了database.secret 配置,staging 除外。有没有办法为这三个配置文件设置一次,对配置文件进行分组或从基本配置文件继承?

【问题讨论】:

    标签: java spring spring-boot configuration


    【解决方案1】:

    您可以在逗号分隔的列表 (qa,playground,production) 中组合配置文件,如下所示:

    spring:
      application:
        name: my-super-app
    common-secret: "foo bar"
    database:
      secret: "default secret"
    this:
      that: "default value..."
    
    ---
    
    spring:
      profiles: staging
    
    
    ---
    
    spring:
      profiles: qa
    
    ---
    
    spring:
      profiles: playground
    
    ---
    
    spring:
      profiles: production
    
    ---
    
    spring:
      profiles: qa,playground,production
    database:
        secret: "foo bar"
    

    您也可以设置一个“共享变量”,如下所示:

    spring:
      application:
        name: my-super-app
    common-secret: "foo bar"
    database:
      secret: "default secret"
    this:
      that: "default value..."
    
    ---
    
    spring:
      profiles: staging
    
    
    ---
    
    spring:
      profiles: qa
    database:
      secret: ${common-secret}
    
    ---
    
    spring:
      profiles: playground
    database:
      secret: ${common-secret}
    
    ---
    
    spring:
      profiles: production
    database:
        secret: ${common-secret}
    

    【讨论】:

    • 是的,但它有一个副作用:common-secret 也将对所有配置文件可见,包括暂存。这对我来说听起来不对。
    • 您的原始问题未指定对解决方案范围的任何限制。我的建议确实有效。我将在我的原始答案中添加一个替代解决方案,以满足您的额外要求。
    • @Mualik 回应您的第一条评论:“common-secret 也将对所有配置文件(包括暂存)可见”:虽然它对暂存配置文件(和所有配置文件)“可见”,但它在fact 对暂存配置文件没有影响,因为暂存配置文件不使用变量 ${common-secret}。它仅对包含 database.secret: ${common-secret} 的配置文件有影响,例如 qa、playground 和 production。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 2018-11-18
    • 2011-09-11
    • 2019-09-26
    • 2016-07-28
    相关资源
    最近更新 更多