【问题标题】:Yml config files "Inheritance" with Spring boot使用 Spring Boot 的 Yml 配置文件“继承”
【发布时间】:2018-06-28 01:23:09
【问题描述】:

我在网上找不到直接的答案。

Spring Boot 的 yml 文件是否相互“继承”?我的意思是,如果我有: application.yml

server:
  port: 80
  host: foo

application-profile1.yml,只有

server:
  port: 90

因此,如果我以 profile1 作为活动配置文件启动 Spring Boot,我是否还将 server.host 属性设置为 foo

【问题讨论】:

    标签: spring-boot spring-profiles


    【解决方案1】:

    这是我的解决方案。

    假设application.yml

    spring:
      profiles: default-server-config
    
    server:
      port: 9801
      servlet:
        context-path: '/ctp'
    

    如果我想使用default-server-config 配置文件,并在我的application-dev.yml 中使用端口8080

    application-dev.yml:

    spring:
      profiles:
        include:
          - default-server-config
          - dev-config
    
    ---
    spring:
      profiles: dev-config
      
    server:
      port: 8080
    

    然后-Dspring.profiles.active=dev

    【讨论】:

      【解决方案2】:

      是的,application.yml 文件的优先级高于任何 application-{profile}.yml 文件。配置文件特定 yml 文件中的属性将覆盖默认 application.yml 文件中的值,并且配置文件特定 yml 文件中不存在的属性将从默认文件加载。它适用于.properties 文件以及bootstrap.ymlbootstrap.properties

      Spring Boot 文档在72.7 Change configuration depending on the environment 段落中提到了它:

      在本例中,默认端口为 9000,但如果 Spring 配置文件“开发”处于活动状态,则端口为 9001,如果“生产”处于活动状态,则端口为 0。

      YAML 文档按照遇到的顺序合并(因此后面的值会覆盖前面的值)。

      要对属性文件做同样的事情,您可以使用application-${profile}.properties 指定配置文件特定的值。

      【讨论】:

      • 所以它可能无法创建 BaseProfile、DerivedProfile1、DerivedProfile2,而派生的配置文件都继承自基础配置文件,对吧?
      • 正确。配置文件特定的application-{profile}.properties 文件继承自基本application.properties 文件,在这种情况下无法进行多级继承。主要是因为在这种情况下,继承顺序并不简单。
      • @tomer.z 实际上我对同一个问题很感兴趣,我找到了适用于属性文件和 yaml 文件的解决方案 - stackoverflow.com/a/60380960/384674
      猜你喜欢
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2018-11-04
      • 2023-01-30
      • 2015-05-08
      • 2017-09-25
      • 1970-01-01
      • 2018-10-29
      相关资源
      最近更新 更多