Yml配置文件中的“继承”与Spring Boot

22

我在网上找不到明确的答案。

Spring Boot的yml文件是否会“继承”彼此?我的意思是如果我有: application.yml 同时包含以下内容:

server:
  port: 80
  host: foo

application-profile1.yml,它只有

server:
  port: 90

如果我使用profile1作为激活的配置文件来启动Spring Boot,那么server.host属性也会被设置为foo吗?

2个回答

17

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

Spring Boot 文档在72.7 更改配置取决于环境段落中提到了它:

在此示例中,默认端口为 9000,但如果 Spring profile 'development' 处于活动状态,则端口为 9001,如果 'production' 处于活动状态,则为 0。

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

使用 application-$ {profile} .properties 来指定特定于配置文件的值可以完成相同的事情。


1
可能不能同时创建BaseProfile、DerivedProfile1和DerivedProfile2,因为这两个派生配置文件都继承自基础配置文件。 - tomer.z
1
正确。特定配置文件application-{profile}.properties会从基础配置文件application.properties继承,而在这种情况下无法进行多级继承。主要是因为在这种情况下,继承的顺序并不直观。 - Szymon Stepniak
@tomer.z 实际上我对同样的问题很感兴趣,并且我找到了解决方案,适用于属性文件和yaml文件 - https://dev59.com/-rPma4cB1Zd3GeqPw9fa#60380960 - Betlista

2
这里是我的解决方案。
假设有一个名为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

很遗憾,“spring.profiles”配置属性已被弃用。 - yusuf

使用新格式仍然是一个好的解决方案: spring: config: activate: on-profile: - default-server-config - dev-config

spring: config: activate: on-profile: - dev-config
- Sorin Dumitru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接