Utilizing Environment Variables in Spring Boot's Application.properties
When deploying a Spring Boot application across various environments, it's essential to avoid hard-coding database credentials in application.properties. To address this, environment variables can be dynamically referenced in the property file.
To leverage this approach, follow these steps:
1. Create System Environment Variables
Create environment variables locally and on any other relevant virtual machines. Name these variables identically to their OpenShift counterparts and assign appropriate values:
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"
2. Referencing Environment Variables in application.properties
To include environment variables in application.properties, use the following syntax:
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}
3. Alternative Approach (Recommended)
However, a more concise and manageable solution proposed by @Stefan Isele is to use Spring profiles:
Spring will automatically read the appropriate property file based on the specified profile.
By following these techniques, you can dynamically configure your Spring Boot application based on the environment in which it's deployed, without having to hard-code sensitive information in application.properties.
The above is the detailed content of How Can I Manage Spring Boot Database Credentials Across Different Environments Using Environment Variables?. For more information, please follow other related articles on the PHP Chinese website!