How to resolve placeholder in properties file with values from another properties file in spring boot application

Anooj VB picture Anooj VB · Feb 26, 2019 · Viewed 9.6k times · Source

My spring boot application has below properties files.

src/main/resources/config/DEV/env.properties
mail.server=dev.mail.domain

src/main/resources/config/QA/env.properties
mail.server=qa.mail.domain

src/main/resources/config/common/env.properties
mail.url=${mail.server}/endpoint

Is it possible to load "common/env.properties" so that it's placeholders will be resolved using the given environment specific properties file. For DEV environment, we want the placeholders in "common/env.properties" to be resolved using values from "DEV/env.properties".

There are answers about how to load multiple properties files and profile based loading but could not find an answer for this particular use case.

Thanks in advance.

Answer

Abbin Varghese picture Abbin Varghese · Feb 26, 2019

2 Options :

  1. Generate the common/application.properties using configuration-maven-plugin and filter files for each environment. It is outdated now.
  2. Use application-<env>.properties for each environment and pass the -Dspring.profiles.active=<env> as VM option in application start up. Spring will automatically take the property from correct file.

In option 2, you will be overwriting whatever is present in application.properties with application-.properties. So you dont have to add only the properties which you need to change per environment.

for eg:

Your application.properties can have

logging.level.root=WARN
logging.level.org.apache=WARN
logging.level.org.springframework=WARN

Your application-dev.properties can have

logging.level.org.springframework=DEBUG

which means, when you are starting application using dev profile, spring takes

logging.level.root=WARN
logging.level.org.apache=WARN
logging.level.org.springframework=DEBUG

edit :

Also, you can try something like below on your class. (Spring will overwrite value in config.properties with values from config-dev.properties). ignoreResourceNotFound will make sure, application will still start with default values even if the corresponding file is not found.

@Configuration
@PropertySource("classpath:config.properties")
@PropertySource(value = "classpath:config-${spring.profiles.active}.properties", ignoreResourceNotFound = true)