When creating an app with Spring (Boot), you may want to get the value from the system environment variable. I will introduce the acquisition method that also serves as a memo.
For example, if you want to connect to DB, you need to set the following in ʻapplication.properties`.
application.properties
###DB connection setting value###
spring.datasource.url=<Database URL>
spring.datasource.username=<username>
spring.datasource.password=<password>
In such a case, if each setting value is acquired from the system environment variable, the following merits can be considered.
① __ There is no need to create a configuration file for each environment. __ The same configuration file can be used in other environments by setting environment variables in advance or by setting them at runtime. It is troublesome to create and manage multiple configuration files (for example, ʻapplication-devXX.properties`) for each environment, so it can be omitted.
In addition, it is not necessary to write the process of setting the file to be read for each environment in the source code. (Because Spring Boot loads ʻapplication.properties` by default)
② __ It leads to improvement of security. __ If you put the information you want to keep secret such as user name and path password in solid in ʻapplication.properties` and upload it to the remote repository, it may cause a security problem.
If you set it as an environment variable, the value will not be written directly, so you can push it to the remote repository with confidence.
Set in the following format.
application.properties
spring.datasource.url=${SPRING_DATASOURCE_URL}
spring.datasource.username=${SPRING_DATASOURCE_USERNAME}
spring.datasource.password=${SPRING_DATASOURCE_PASSWORD}
For example, if you explain spring.datasource.username = $ {SPRING_DATASOURCE_USERNAME}
,
(1) First, add a variable such as SPRING_DATASOURCE_USERNAME = HogeHoge
to the system environment variables.
For the environment variable name, replace the target value ". "
In the configuration file with " _ "
and then capitalize it.
spring.datasource.username
⇒ spring_datasource_username
⇒ SPRING_DATASOURCE_USERNAME
(2) In ʻapplication.properties, set the system environment variable name to the value enclosed in
$ {} , such as
$ {SPRING_DATASOURCE_USERNAME} `.
The system environment variables are now available from ʻapplication.properties`.
If you are developing using eclipse or sts, after adding the system environment variables, you should restart the Spring Boot app on eclipse (sts) or restart it once when you try to run JUnit. Is good. System environment variables may not be read and an error may occur.
Probably because the system environment variable is read and used when eclipse (sts) is started, it is not reflected even if the environment variable is added during startup, but the details are unknown.
System environment variables can be used from the configuration file! !! !! !! !! (Wazap)
Recommended Posts