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).
Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
Now, when your Spring Boot application starts, it will be given those environment variables, which will override your application. properties .
Spring boot provides command line configuration called spring.config.name using that we can change the name of application. properties. Here properties file name will be my-config.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With