Spring allows applications to read configuration values directly from environment variables, making it easy to externalize configuration and deploy the same application across different environments without code changes. Environment variables are commonly used for database credentials, API keys, server settings, and other environment-specific configurations.
Key Points: • Environment variables help keep sensitive and environment-specific settings outside the application code. • Values can be injected using @Value, Environment, or @ConfigurationProperties. • This approach improves security, portability, and maintainability across development, testing, and production environments.
Example: Suppose an application requires a database URL that differs between development and production. Instead of hardcoding the value, an environment variable can be defined and injected at runtime.
Code Example:
Using @Value:
@Component
public class DatabaseConfig {
@Value("${DB_URL}")
private String databaseUrl;
public void printUrl() {
System.out.println(databaseUrl);
}
}Using Environment Interface:
@Component
public class DatabaseConfig {
@Autowired
private Environment environment;
public void printUrl() {
String url =
environment.getProperty("DB_URL");
System.out.println(url);
}
}Using application.properties:
app.name=${APP_NAME:MyApplication}
The value of APP_NAME is taken from the environment variable. If the variable is not available, "MyApplication" is used as the default value.
Common Use Cases: • Database URLs and credentials. • API keys and tokens. • Server ports and hostnames. • Cloud and containerized deployments. • Environment-specific configurations.
Best Practice: • Store sensitive information in environment variables instead of source code. • Use @ConfigurationProperties for large configuration groups. • Provide default values where appropriate to avoid startup failures.
Interview Tip: A concise interview answer is: Environment variables can be injected into Spring applications using @Value, the Environment interface, or @ConfigurationProperties. This externalizes configuration, improves security, and allows the same application to run across different environments without code modifications.