Back to all reviewers

Environment variables best practices

spring-projects/spring-boot
Based on 2 comments
Other

When working with environment variables in configuration files, follow these practices to ensure reliability and testability: 1. Use placeholder syntax `${ENV_VAR}` to reference environment variables in both properties and YAML configuration files

Configurations Other

Reviewer Prompt

When working with environment variables in configuration files, follow these practices to ensure reliability and testability:

  1. Use placeholder syntax ${ENV_VAR} to reference environment variables in both properties and YAML configuration files
  2. Provide default values using the ${ENV_VAR:default-value} syntax to ensure the application functions even when environment variables are not set
  3. For testing environment variable-dependent code, design components to accept injectable Map objects rather than using reflection-based libraries

Example of proper environment variable usage in YAML:

environments:
  dev:
    url: ${DEV_ENV_URL}
    name: ${DEV_ENV_NAME:development-environment}

When testing code that depends on environment variables, prefer dependency injection instead of reflection:

// Instead of using reflection-based libraries to modify System.getenv()
public class ConfigReader {
    private final Map<String, String> env;
    
    // For production use
    public ConfigReader() {
        this(System.getenv());
    }
    
    // For testing use
    public ConfigReader(Map<String, String> env) {
        this.env = env;
    }
    
    public String getConfig(String key, String defaultValue) {
        return env.getOrDefault(key, defaultValue);
    }
}
2
Comments Analyzed
Other
Primary Language
Configurations
Category

Source Discussions