Configuring Spring Boot Applications with Environment Variables
Spring Boot simplifies the development of Java applications, but configuring these applications for different environments (local development, testing, production) can be challenging. Hardcoding configuration values directly into your application’s properties files is generally a bad practice, as it requires code changes to deploy the application in different environments. This tutorial demonstrates how to leverage environment variables to create flexible and portable Spring Boot applications.
Why Use Environment Variables?
Environment variables offer several key advantages:
- Configuration Flexibility: Easily switch configurations without modifying code.
- Portability: Configurations are externalized, making your application portable across different environments.
- Security: Sensitive information like passwords and API keys can be stored outside of your codebase, enhancing security.
- DevOps Integration: Environment variables are well-suited for automation and integration with DevOps tools like Jenkins, Docker, and Kubernetes.
Setting Environment Variables
Environment variables are set outside of your application code, at the operating system or container level. The specific method for setting them varies depending on your operating system.
- Linux/macOS: Use the
export
command in your terminal. For example:export DB_HOST=localhost export DB_PORT=3306 export DB_USERNAME=root export DB_PASSWORD=secret
- Windows: Use the
set
command in your command prompt, or configure them through the System Properties (Environment Variables) dialog.
Configuring Spring Boot to Use Environment Variables
Spring Boot provides a straightforward mechanism to access environment variables within your application. You can directly reference environment variables within your application.properties
or application.yml
file using the ${}
syntax.
Example using application.properties
:
spring.datasource.url=${DB_HOST}:${DB_PORT}/your_database
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
In this example, Spring Boot will look for environment variables named DB_HOST
, DB_PORT
, DB_USERNAME
, and DB_PASSWORD
and use their values to configure the database connection. If an environment variable is not found, Spring Boot will typically use a default value (if specified in the properties file) or throw an exception.
Accessing Environment Variables in Java Code (Optional)
While accessing environment variables directly in properties files is usually sufficient, you can also access them programmatically within your Java code using System.getenv()
.
import java.util.Map;
public class ConfigReader {
public static void main(String[] args) {
Map<String, String> env = System.getenv();
String databaseUrl = env.get("DB_URL");
String username = env.get("DB_USERNAME");
if (databaseUrl != null && username != null) {
System.out.println("Database URL: " + databaseUrl);
System.out.println("Username: " + username);
} else {
System.out.println("Required environment variables not set.");
}
}
}
Using Spring Profiles for More Advanced Configuration
For complex applications with multiple environments, consider using Spring Profiles. Profiles allow you to define different sets of configurations for each environment.
-
Create Profile-Specific Properties Files: Create files named
application-{profile}.properties
orapplication-{profile}.yml
, where{profile}
is the name of your profile (e.g.,application-local.properties
,application-dev.properties
,application-prod.properties
). -
Define Configurations in Profile Files: Place environment-specific configurations in the appropriate profile file.
# application-local.properties spring.datasource.url=jdbc:mysql://localhost:3306/local_db spring.datasource.username=local_user spring.datasource.password=local_password # application-prod.properties spring.datasource.url=jdbc:mysql://prod_host:3306/prod_db spring.datasource.username=prod_user spring.datasource.password=prod_password
-
Activate the Profile: Activate the desired profile using one of the following methods:
- Set
spring.profiles.active
Environment Variable: Set thespring.profiles.active
environment variable to the name of the profile you want to activate. - Specify Profile as a Command-Line Argument: Use the
--spring.profiles.active={profile}
command-line argument when running your application. - Set
activeProfiles
Programmatically: Use aSpringApplicationBuilder
to set the active profiles in your Java code.
- Set
Best Practices
- Consistent Naming: Use a consistent naming convention for your environment variables (e.g., all uppercase with underscores).
- Secure Sensitive Data: Never store sensitive data directly in your code or version control system. Use environment variables or a dedicated secrets management solution.
- Default Values: Provide reasonable default values for environment variables to prevent application failures when they are not explicitly set.
- Documentation: Document the required environment variables for your application, including their purpose and default values.