Sub topic 1
Why Spring Boot Externalizes Configuration
Prerequisites
Assume you know basic Java, Spring beans, dependency injection, and .properties or YAML syntax. Spring Boot externalizes configuration by keeping values such as ports, database URLs, and feature flags outside compiled Java code. The same application can then run in development, testing, and production with different settings.
External configuration also makes deployment safer. You can provide a secret or endpoint through the environment without committing it to source control.
Writing Configuration Files
Spring Boot commonly reads application.properties and application.yaml.
server.port=8080
app.mail.host=localhost
app.mail.retry-attempts=3The equivalent YAML is:
server:
port: 8080
app:
mail:
host: localhost
retry-attempts: 3YAML represents nesting with indentation. Property names use dots. Do not mix tabs and spaces in YAML.
Property Sources and Which Value Wins
Spring Boot combines values from several sources. A simplified precedence order, from higher to lower priority, is:
- Command-line arguments, such as
--server.port=9000 - Environment variables, such as
SERVER_PORT=9000 - Profile-specific configuration files
application.propertiesorapplication.yaml- Default values in code
If several sources define server.port, the higher-priority source wins. This lets deployment settings override values packaged inside the application.
Reading Single Values
Use @Value for a small number of individual values:
@Component
class MailClient {
MailClient(@Value("${app.mail.host:localhost}") String host) {
System.out.println(host);
}
}The text after : is a fallback. For programmatic access, inject Environment:
@Component
class StartupMessage {
StartupMessage(Environment environment) {
String port = environment.getProperty("server.port", "8080");
System.out.println("Port: " + port);
}
}Both APIs return individual values. For related settings, @ConfigurationProperties is usually clearer and provides type conversion.
Relaxed Binding
Spring Boot uses relaxed binding, which accepts several names for the same property. app.mail.retry-attempts can be supplied as:
app.mail.retry-attemptsapp.mail.retryAttemptsAPP_MAIL_RETRY_ATTEMPTS
The environment-variable form replaces periods with underscores, uses uppercase letters, and commonly replaces hyphens with underscores.
Exercise
If application.yaml sets server.port to 8080 and the command line supplies --server.port=9000, which value does Spring Boot use?
Show answer
It uses 9000 because command-line arguments have higher precedence.