Yml 配置文件 "Inheritance" 和 Spring 引导

Yml config files "Inheritance" with Spring boot

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

Spring Boot 的 yml 文件 "inherit" 相互吗?我的意思是如果我有: application.yml 其中有

server:
  port: 80
  host: foo

application-profile1.yml只有

server:
  port: 90

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

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

Spring 引导文档在 72.7 Change configuration depending on the environment 段中提到它:

In this example the default port is 9000, but if the Spring profile ‘development’ is active then the port is 9001, and if ‘production’ is active then it is 0.

The YAML documents are merged in the order they are encountered (so later values override earlier ones).

To do the same thing with properties files you can use application-${profile}.properties to specify profile-specific values.

这是我的解决方案。

假设 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