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
When working with environment variables in configuration files, follow these practices to ensure reliability and testability:
${ENV_VAR}
to reference environment variables in both properties and YAML configuration files${ENV_VAR:default-value}
syntax to ensure the application functions even when environment variables are not setExample 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);
}
}
Enter the URL of a public GitHub repository