22

I couldn't find a straight answer online.

Do Spring Boot's yml files "inherit" from each other? I mean if I have: application.yml which has

server:
  port: 80
  host: foo

and application-profile1.yml which has only

server:
  port: 90

So if I start my Spring Boot with profile1 as active profile, will I also have server.host property set to foo?

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
tomer.z
  • 1,033
  • 1
  • 10
  • 25

2 Answers2

17

Yes, application.yml file has higher precedence over any application-{profile}.yml file. Properties from profile specific yml file will override values from the default application.yml file and properties that do not exist in profile specific yml file will be loaded from the default one. It applies to .properties files as well as to bootstrap.yml or bootstrap.properties.

Spring Boot documentation mentions it in 72.7 Change configuration depending on the environment paragraph:

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.

Community
  • 1
  • 1
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • 1
    So its probably not possible to create BaseProfile, DerivedProfile1, DerivedProfile2 while both the derived profiles inherit from the base one right? – tomer.z Jan 19 '18 at 00:30
  • 1
    Correct. Profile specific `application-{profile}.properties` file inherits from base `application.properties` file and there is no way to do multi level inheritence in this case. Mostly because in this case order of the inheritance wouldn't be straightforward. – Szymon Stepniak Jan 19 '18 at 08:51
  • @tomer.z Actually I was interested in same question and I found a solution for both property files as well as for yaml files - https://stackoverflow.com/a/60380960/384674 – Betlista Mar 04 '20 at 12:11
2

Here is my solution.

Assume application.yml:

spring:
  profiles: default-server-config

server:
  port: 9801
  servlet:
    context-path: '/ctp'

If I want use default-server-config profile, and use port 8080 in my application-dev.yml

application-dev.yml:

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

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

Then -Dspring.profiles.active=dev

MLavoie
  • 9,671
  • 41
  • 36
  • 56
  • Unfortunately, 'spring.profiles' configuration property is deprecated – yusuf Oct 14 '22 at 12:55
  • It's still a good solution with the new format: spring: config: activate: on-profile: - default-server-config - dev-config --- spring: config: activate: on-profile: - dev-config – Sorin Dumitru Oct 28 '22 at 13:34