Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 66 ยท Auto-Configuration and Configuration

Type-Safe @ConfigurationProperties

Bind application.yml to typed Java records with @ConfigurationProperties: nested objects, durations, data sizes, validation, defaults and configuration metadata.

Scattering @Value("${...}") annotations through a project works for two or three settings. At ten, you have string keys repeated across files, no single place that shows what the application can be configured with, and type errors that surface at runtime. Spring Boot's answer is @ConfigurationProperties: you describe a group of settings as a Java type, and Boot binds the values from application.yml, environment variables and command-line arguments into it at startup.

The result is configuration that is typed, grouped, validated and documented. If a port is not a number, the application fails to start with a message that names the property and where its value came from. This lesson uses Java records, which suit configuration well because the values never change after binding.

Real Spring Boot cannot run here, so the Spring code is read-only. A runnable stand-in at the end builds a small reflection-based binder, so you can watch how a flat property map becomes a nested record, including defaults, durations, sizes and validation.

A first properties record

Say your application sends mail. Define the settings as a record and give them a prefix:

Java
import java.time.Duration;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;

@ConfigurationProperties(prefix = "app.mail")
public record MailProperties(
        String host,
        @DefaultValue("25") int port,
        @DefaultValue("false") boolean tls,
        @DefaultValue("5s") Duration timeout,
        List<String> recipients) {
}

And the matching configuration:

YAML
app:
  mail:
    host: smtp.example.com
    port: 587
    tls: true
    timeout: 10s
    recipients:
      - [email protected]
      - [email protected]

A record with one constructor is bound by constructor binding automatically: Boot calls the canonical constructor with the converted values. @DefaultValue supplies a value when nothing is configured, so port is 25 unless you say otherwise. Components with no value and no default get null (or zero, false for primitives).

Names follow relaxed binding. The component maxSize maps to the key max-size in files and APP_MAIL_MAXSIZE in an environment variable; see Properties, YAML and Externalized Config. The prefix itself must be lowercase kebab-case.

Registering the record

Boot does not guess which types to bind. Pick one of two ways:

Java
// Option 1: scan for @ConfigurationProperties classes (put it on your application class)
@SpringBootApplication
@ConfigurationPropertiesScan
public class ShopApplication { /* ... */ }

// Option 2: register specific types, for example in a starter's auto-configuration
@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class MailConfig { /* ... */ }

Now MailProperties is a normal bean. Inject it into any component, preferably through the constructor:

Java
@Service
public class MailSender {

    private final MailProperties properties;

    public MailSender(MailProperties properties) {
        this.properties = properties;
    }
}

Records bound by constructor are immutable, so one component cannot change another's settings at runtime. Older code uses classes with getters and setters (JavaBean binding), which still works but offers no such guarantee.

Nested groups

Related settings can live in a nested record. The YAML mirrors the structure:

Java
@ConfigurationProperties(prefix = "app.client")
public record ClientProperties(
        @DefaultValue("https://api.example.com") String baseUrl,
        @DefaultValue Retry retry) {

    public record Retry(
            @DefaultValue("3") int maxAttempts,
            @DefaultValue("200ms") Duration delay) {
    }
}
YAML
app:
  client:
    retry:
      max-attempts: 5

The bare @DefaultValue on the retry component matters: it tells Boot to create the nested record with its own defaults when no app.client.retry.* keys exist. Without it, a nested record whose keys are all missing is bound as null, and the first call to properties.retry().maxAttempts() throws a NullPointerException.

Durations and data sizes

Configuration is full of time spans and sizes, and plain int fields hide the unit. Boot converts readable strings to proper types:

Type Accepted values Example
Duration 30s, 5m, 2h, 1d, 200ms, or ISO PT30S timeout: 10s
DataSize 512B, 10KB, 5MB, 1GB max-upload: 5MB
Period 7d, 2w, 1y retention: 30d

A bare number such as timeout: 10 is read in milliseconds for a Duration unless you annotate the component with @DurationUnit(ChronoUnit.SECONDS). Writing the unit explicitly avoids that guessing; the same goes for @DataSizeUnit on a DataSize. Using Duration instead of long timeoutMillis also means your code can call timeout.toSeconds() without conversion mistakes.

Validation

Settings that are wrong should stop the application at startup, not fail at 3 a.m. when the code path first runs. Add @Validated and Jakarta Bean Validation constraints (with the validation starter on the classpath):

Java
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;

@Validated
@ConfigurationProperties(prefix = "app.mail")
public record MailProperties(
        @NotBlank String host,
        @DefaultValue("25") @Min(1) @Max(65535) int port,
        @Valid @DefaultValue Pool pool) {

    public record Pool(@DefaultValue("10") @Min(1) int maxSize) {
    }
}

Put @Valid on a nested record so its constraints are checked too. With host empty and pool.max-size: 0, Boot stops with a report like this (shortened):

TEXT
***************************
APPLICATION FAILED TO START
***************************

Binding to target MailProperties failed:

    Property: app.mail.host
    Value: ""
    Origin: class path resource [application.yml] - 3:11
    Reason: must not be blank

    Property: app.mail.pool.max-size
    Value: "0"
    Reason: must be greater than or equal to 1

Every violation is listed at once, with the property name, the bad value and the file position it came from. That report is the main reason to prefer typed binding.

A binder in plain Java

How can a library turn app.mail.pool.max-size=0 into a record with a nested record? With reflection: read the record's components, derive a key for each, convert the string to the component's type, and call the constructor. The stand-in below does exactly that for strings, numbers, booleans, Duration, a small DataSize type, lists and nested records. It also supports @Default, @NotBlank and @Min annotations that mimic the real ones, and it collects every error before reporting, as Boot does.

Java A reflection-based properties binder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: reading record components, converting text to the component type, applying defaults, and reporting all problems together. What is the stand-in: Boot's Binder handles every Java type, maps, collections with many syntaxes, Origin tracking, JavaBean binding, conversion service customization, and runs real Jakarta Validation. Note also that this stand-in always builds nested records; in real Boot you need @DefaultValue for that, as shown above.

The configuration metadata processor

IDEs show completion and documentation for app.mail.* because of a generated file. Add the processor to your build and every @ConfigurationProperties class produces META-INF/spring-configuration-metadata.json at compile time:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Javadoc on the record (@param tags) becomes the description users see. For the full story on shipping metadata inside a library, see Writing Your Own Starter.

Custom converters and common mistakes

If a component uses your own type, register a converter bean annotated with @ConfigurationPropertiesBinding so Boot can turn text into that type. Typical mistakes:

  • Forgetting registration. A properties record that is neither scanned nor enabled is never bound, and injecting it fails with "no qualifying bean".
  • Camel-case keys in YAML. Write max-size, not maxSize; both bind, but only kebab-case is portable.
  • A missing nested default. Add @DefaultValue to nested record components you want to exist even when unconfigured.
  • Secrets in the record's toString. A record prints every component, so never log one that holds a password; override toString or keep secrets in a separate component type.
  • Mixing both styles. Do not use @Value for keys that already live in a properties class.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @DefaultValue("25") on the record component int port do?

    The default applies when no source defines the key. Any configured value overrides it.
  2. 2. A nested record has no configured keys and its component has no @DefaultValue. What does constructor binding give you?

    Without a default the nested object is bound as null. Add a bare @DefaultValue to get an instance with its own defaults.
  3. 3. Why add @Validated to a properties class?

    Validation runs while binding, so bad configuration stops the application at startup with the property names, values and origins.
  4. 4. For a Duration component, what does timeout: 10s mean compared with a bare timeout: 10?

    The unit suffix removes the guessing. Without it, the default unit is milliseconds.

Summary

  • @ConfigurationProperties binds a prefix of your configuration into a typed object; records with constructor binding give immutable settings.
  • Register the type with @ConfigurationPropertiesScan or @EnableConfigurationProperties.
  • @DefaultValue provides fallbacks, and a bare @DefaultValue on a nested record creates it when nothing is configured.
  • Duration, DataSize and Period read human-friendly values like 10s and 5MB.
  • @Validated plus Jakarta constraints stops the app at startup with a clear report; the metadata processor gives IDE completion.

Next: Profiles and Environment-Specific Config.