Set Spring Boot application.properties based on Environment Variable

Tanishq dubey :

I have a Spring Boot application that will run in various environments, and based on the environment it runs in, it will connect to a different database. I have a few application.properties files, one for each environment which look like such:

application-local.properties:

spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=dbuser
spring.datasource.password=123456789

application-someserver.properties:

spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://someserver:5432/myproddb
spring.datasource.username=produser
spring.datasource.password=productionpass

etc. etc.

On each of my environments, I have a environment variable called MYENV which is set to the type of environment it is, for example local or someserver (the name of the application-{env}.properties files perfectly matches the environment name).

How can I get spring boot to read this environment variable and automatically choose the correct .properties file? I don't want to have to do the whole -Dspring.profiles.active=someserver because of the way this package is deployed (it will not be running as a jar).

Ali Dehghani :

How can I get spring boot to read this environment variable and automatically choose the correct .properties file?

Tell Spring Boot to select the Active Profile from the MYENV property or environment variable. One way of doing this is to add the following into your application.properties:

spring.profiles.active=${MYENV}

This way Spring Boot will set spring.profiles.active to the value of MYENV environment variable.

I don't to have to do the whole -Dspring.profiles.active=someserver because of the way this package is deployed (it will not be running as a jar)

You can use the corresponding environment variable to that spring.profiles.active, if you don't like to pass a system property through -D arguments. That corresponding environment variable is SPRING_PROFILES_ACTIVE. For example if you set the SPRING_PROFILES_ACTIVE to local, the local profile will be activated. If you're insisting to use MYENV environment variable, the first solution is the way to go.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452958&siteId=1