Home > Java > javaTutorial > How Can I Use Environment Variables to Manage Database Credentials in a Spring Boot Application?

How Can I Use Environment Variables to Manage Database Credentials in a Spring Boot Application?

Mary-Kate Olsen
Release: 2024-11-27 04:31:15
Original
543 people have browsed it

How Can I Use Environment Variables to Manage Database Credentials in a Spring Boot Application?

Using Environment Variables in Spring Boot's application.properties

Background

Consider a Spring Boot application connecting to MySQL in multiple environments (local, Jenkins, OpenShift). To avoid hardcoding MySQL credentials, you need to make application.properties dynamic. As a proposed solution, you've created system environment variables with the same names as OpenShift environment variables and assigned appropriate values.

Using Environment Variables in application.properties

To incorporate system environment variables into application.properties, add the following lines:

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

When Spring Boot initializes, it will retrieve these environment variables and substitute them into your configuration.

Alternative Approach

An alternative approach is to use Spring Boot profiles. Add the following to application.properties:

spring.profiles.active=local
Copy after login

Create a new property file named application-local.properties containing:

spring.datasource.url=jdbc:mysql://localhost
spring.datasource.username=root
spring.datasource.password=123asd
Copy after login

Spring Boot will automatically load the properties from application-{profile-name}.properties based on the value of spring.profiles.active.

The above is the detailed content of How Can I Use Environment Variables to Manage Database Credentials in a Spring Boot Application?. 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