'Spring boot - taking different properties from 2 ymls

I have 2 yml files, one is for common for all applications and the other one is for specific application.

application.yml

ui-service.yml

in application.yml
spring:
  profiles: DEV
  jmx:
    enabled: false
  datasource:
    url:...urlA
    driver-class-name:...
    username: ...
    password: ...
  jpa:...
...

in ui-service.yml
spring:
  profiles: DEV
  jmx:
    enabled: false
  jpa:..
  datasource:
    url: urlB
    driver-class-name:
    username: //
    password: ..
..

the purpose of having two separate ymls is that some of the applications can use datasource in application.yml but some of applications need to use different datasource. when we have spring:.... in ui-service.yml, does this replace whole section of spring: ... properties in application.yml? or only the properties that's in both yml will be replaced? for example, if i remove profiles: DEV from ui-service.yml, will it get it from application.yml but datasource from ui-service.yml?

Thanks!



Solution 1:[1]

First of all you have to take three application.yml files :

  1. application.yml(In this yml file you have to mention which yml file is using either application-development.yml or application-production.yml )
  2. application-development.yml (Specific configuration)
  3. application-production.yml (Specific configuration)

for ex:

application-development.yml:

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: "jdbc:mysql://localhost:3306/developmentdb"
    username: development
    password: ***********

application-production.yml:

spring:
      datasource:
        driverClassName: com.mysql.cj.jdbc.Driver
        url: "jdbc:mysql://localhost:3306/productiondb"
        username: production
        password: ***********

If you want to run your code with any one of above two yml file, you have to mention in main application.yml file that is shown below..,

Case 1: If we want development yml: code will be like this

spring:
  profiles:
    active: development

Case 2: If we want production yml: code will be like this

spring:
  profiles:
    active: production

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1