In Spring Boot, the application.properties file contains configuration settings for the application. When the application runs on different environments (local, Jenkins, OpenShift), it's often desired to dynamically adjust these settings. One approach to achieve this is by using environment variables.
To set environment variables, create system environment variables locally and in the Jenkins VM. Ensure that these variables have the same names and values as used in OpenShift. For example:
export OPENSHIFT_MYSQL_DB_HOST="jdbc:mysql://localhost" export OPENSHIFT_MYSQL_DB_PORT="3306" export OPENSHIFT_MYSQL_DB_USERNAME="root" export OPENSHIFT_MYSQL_DB_PASSWORD="123asd"
To use environment variables in application.properties, simply include them using the syntax ${VARIABLE_NAME}. For example:
spring.datasource.url = ${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/"nameofDB" spring.datasource.username = ${OPENSHIFT_MYSQL_DB_USERNAME} spring.datasource.password = ${OPENSHIFT_MYSQL_DB_PASSWORD}
Note: It's also possible to create environment variables using the Spring Environment object, but as suggested by @Stefan Isele, using direct variable substitution in application.properties is a simpler approach.
An alternative to using environment variables is to use Spring profiles. With this approach, you can create multiple application.properties files, each tailored to a specific environment. Spring will automatically load the appropriate file based on the value of the spring.profiles.active property, which can be set as an environment variable or through command-line arguments. For example, you could create application-local.properties, application-jenkins.properties, and application-openshift.properties files. In this case, you would set the OPENSHIFT_MYSQL_DB_HOST variable and spring.profiles.active=openshift when deploying to OpenShift.
By using profiles, you can avoid exposing database credentials or other sensitive information in environment variables, as they are only used to configure the active profile.
The above is the detailed content of How Can I Use Environment Variables to Configure My Spring Boot Application in Different Environments?. For more information, please follow other related articles on the PHP Chinese website!