Typed config with @ConfigurationProperties
Bind a group of YAML keys to a validated Java record instead of scattering @Value.
Open this lesson in the learning hubKey points
@Value("${shop.currency}")works, but the key is a string and mistakes surface at runtime.@ConfigurationPropertiesbinds a whole prefix to a typed object. Records work and are immutable.- Register it with
@EnableConfigurationProperties, or scan all of them with@ConfigurationPropertiesScan. - Add
@Validatedplus Bean Validation annotations and bad config fails at startup, not at 3am. - Binding is relaxed:
max-items-per-orderandMAX_ITEMS_PER_ORDERboth reachmaxItemsPerOrder. - Durations and sizes bind natively:
30sto aDuration,10MBto aDataSize.
Example
import java.time.Duration;
import jakarta.validation.constraints.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "shop")
public record ShopProperties(
@NotBlank String currency,
@Min(1) @Max(100) int maxItemsPerOrder,
@DefaultValue("30s") Duration checkoutTimeout) {
}
// Enable scanning once, on the main class:
// @ConfigurationPropertiesScan
// @SpringBootApplication
// public class ShopApplication { ... }
@Service
class PricingService {
private final ShopProperties props;
PricingService(ShopProperties props) { this.props = props; }
}
Typed, validated config turns a production misconfiguration into a startup failure.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.