Typed config with @ConfigurationProperties

Spring Boot · lesson 8 of 39 · 3 min read

Bind a group of YAML keys to a validated Java record instead of scattering @Value.

Open this lesson in the learning hub

Key points

  • @Value("${shop.currency}") works, but the key is a string and mistakes surface at runtime.
  • @ConfigurationProperties binds a whole prefix to a typed object. Records work and are immutable.
  • Register it with @EnableConfigurationProperties, or scan all of them with @ConfigurationPropertiesScan.
  • Add @Validated plus Bean Validation annotations and bad config fails at startup, not at 3am.
  • Binding is relaxed: max-items-per-order and MAX_ITEMS_PER_ORDER both reach maxItemsPerOrder.
  • Durations and sizes bind natively: 30s to a Duration, 10MB to a DataSize.

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.