Home > Java > javaTutorial > How Can I Manage Spring Boot Database Credentials Across Different Environments Using Environment Variables?

How Can I Manage Spring Boot Database Credentials Across Different Environments Using Environment Variables?

Mary-Kate Olsen
Release: 2024-12-02 11:37:11
Original
428 people have browsed it

How Can I Manage Spring Boot Database Credentials Across Different Environments Using Environment Variables?

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"
Copy after login

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}
Copy after login

3. Alternative Approach (Recommended)

However, a more concise and manageable solution proposed by @Stefan Isele is to use Spring profiles:

  • Create multiple property files named application-{profile-name}.properties.
  • Set the environment variable spring.profiles.active to the desired profile (e.g., application-local.properties).

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template