Sub topic 2
Overriding with Environment Variables and Command-Line Arguments
Assume you know basic Java, Spring beans, dependency injection, and YAML. Spring Boot externalizes configuration so the same application can use different values in development, tests, and production.
Environment and Command-Line Overrides
Command-line arguments have higher precedence than environment variables, and both normally override values packaged in application.yaml.
java -jar app.jar --spring.profiles.active=prod --app.mail.port=2525
SPRING_PROFILES_ACTIVE=prod APP_MAIL_HOST=smtp.internal.example \
java -jar app.jarSpring Boot uses relaxed binding for environment variables. The property app.mail.retry-attempts becomes APP_MAIL_RETRY_ATTEMPTS. Dots and hyphens become underscores, and names are uppercase.
Binding and Validating a Property Group
Use @ConfigurationProperties when related settings form one configuration object. This gives you typed fields instead of repeated string lookups.
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "app.mail")
public record MailProperties(
@NotBlank String host,
@Min(1) @Max(65535) int port,
@NotBlank String sender,
@DefaultValue("3") int retryAttempts) {
}Register the class with @ConfigurationPropertiesScan on your application class. Spring then maps app.mail.host, app.mail.port, and related keys into MailProperties.
Validation runs during startup. A missing host or a port outside the allowed range prevents the application from starting, instead of allowing a bad value to fail later.
Profiles and Profile-Specific YAML
A profile is a named set of configuration and beans for an environment. Activate one with --spring.profiles.active=prod or SPRING_PROFILES_ACTIVE=prod.
YAML can contain multiple documents. The second document applies only when the prod profile is active.
app:
mail:
host: localhost
port: 1025
sender: [email protected]
---
spring:
config:
activate:
on-profile: prod
app:
mail:
host: smtp.example.com
port: 587Exercise
Which value does the application use for app.mail.port when YAML contains 587 and the command line contains --app.mail.port=2525?
Show answer
It uses 2525, because the command line has higher precedence than the packaged YAML configuration.