Skip to content
javahacks.dev
Spring Boot

How to Bind Configuration Properties to Typed Classes

Bind application.yml values to typed Java records with @ConfigurationProperties: prefixes, nested objects, lists, durations, defaults and relaxed names.

6 min read
Summarize in AI
Flat illustration of settings switches, a slider and a gear, with the Spring Boot, Spring, Apache Maven, OpenJDK and JUnit5 logos.

Reading settings with @Value is fine for one or two keys. For a group, a typed class is clearer, checked by the compiler and testable on its own. Spring Boot's binding mechanism handles it. This uses Spring Boot 4 and JDK 25. The difference between the two styles is in Value versus ConfigurationProperties.

A properties record

YAML
shop:
  mail:
    host: smtp.example.com
    port: 587
    reply-to: [email protected]
    timeout: 5s
    retries: 3
    allowed-domains:
      - example.com
      - example.org
  limits:
    max-upload: 10MB
java
@ConfigurationProperties(prefix = "shop.mail")
public record MailProperties(
        String host,
        int port,
        String replyTo,
        Duration timeout,
        @DefaultValue("2") int retries,
        List<String> allowedDomains) { }

Register it. The easiest way is to scan:

java
@SpringBootApplication
@ConfigurationPropertiesScan
class App { }

or name it explicitly with @EnableConfigurationProperties(MailProperties.class) on a configuration class. Then inject it like any bean:

java
@Service
class Mailer {
    private final MailProperties props;
    Mailer(MailProperties props) { this.props = props; }
}

What Boot converts

Property textJava type
5s, 200ms, PT30SDuration
10MB, 512KBDataSize
a,b,c or YAML listList<String>, Set, arrays
ENABLED or enabledenum constant
trueboolean
A map of keysMap<String, X>

Nested objects use nested records:

java
public record LimitsProperties(Uploads uploads, int maxItems) {
    public record Uploads(DataSize maxSize, List<String> types) { }
}

binding shop.limits.uploads.max-size.

Relaxed binding

The same property can be written in several ways, and Boot treats them alike:

SourceForm
.properties and YAMLshop.mail.reply-to (kebab case, recommended)
Environment variableSHOP_MAIL_REPLYTO
Camel caseshop.mail.replyTo

Use kebab case in files and let the environment variable form follow. That makes container configuration work without translation, see Boot configuration precedence.

Mutable classes and constructor binding

For classes rather than records, Boot uses constructor binding if the class has a single constructor with parameters, and JavaBean setter binding otherwise. Records are the preferred form because immutability stops code from changing configuration at runtime. Use @ConstructorBinding only when the class has several constructors.

Metadata for IDEs

Add the annotation processor and your IDE completes and documents the keys in application.yml:

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

Javadoc comments on fields become descriptions in the generated metadata.

Errors

A missing required value with a primitive type fails with Binding to target ... failed, naming the property. An unknown key is ignored by default; set ignoreUnknownFields = false to catch typos. A value that cannot convert, such as timeout: soon, fails at startup with the property and origin file. To fail early on bad values, add validation, as in validating configuration properties.

Testing

Bind in a test without the full application:

java
@Test
void bindsMailProperties() {
    new ApplicationContextRunner()
        .withUserConfiguration(MailConfig.class)
        .withPropertyValues("shop.mail.host=h", "shop.mail.port=25")
        .run(ctx -> assertThat(ctx.getBean(MailProperties.class).port()).isEqualTo(25));
}

Validation fails the start, which is what you want

Annotate the properties class with @Validated and put Bean Validation constraints on the fields, and a missing or malformed setting stops the application at startup with a message naming the property:

java
@ConfigurationProperties("shop.mail")
@Validated
record MailProperties(@NotBlank String host, @Min(1) @Max(65535) int port, @DefaultValue("5s") Duration timeout) {}

The error reads Binding to target ... failed followed by the property name, the rejected value and the constraint. A service that refuses to start with a clear line beats one that starts and fails on the first email at three in the morning. Add jakarta.validation support by including spring-boot-starter-validation, since without it the annotations are ignored silently, which is the most common reason a constraint appears to do nothing.

Types Boot converts for you

Binding converts more than strings. A Duration accepts 30s, 5m or ISO-8601 PT5M, a DataSize accepts 10MB, lists bind from comma-separated values or indexed keys, and maps bind from nested keys. Use these types instead of writing timeoutSeconds and maxSizeBytes fields, because the unit then lives in the value where an operator can see it. A bare timeout=30 for a Duration binds as milliseconds unless you annotate the field with @DurationUnit, so prefer explicit suffixes in configuration files.

Secrets and environment variables

Environment variables bind through relaxed rules: SHOP_MAIL_HOST sets shop.mail.host, and a list element is SHOP_MAIL_RECIPIENTS_0. That makes the same record work in a container without a file. Keep secrets out of the properties file in the repository. Bind them from the environment or from a mounted file with spring.config.import=configtree:/run/secrets/, and never print the properties object in a log, since the generated toString() of a record includes every field. If a record holds a password, override toString() or give the secret its own type that masks itself.

Testing a properties class

Test binding without starting the whole application, using ApplicationContextRunner:

java
new ApplicationContextRunner()
    .withUserConfiguration(MailConfig.class)
    .withPropertyValues("shop.mail.host=smtp.example.com", "shop.mail.port=70000")
    .run(ctx -> assertThat(ctx).hasFailed());

One test for the happy path and one per important constraint cost milliseconds and catch the day somebody loosens a validation rule or renames a key without updating the files that set it.

Why not just use @Value

@Value("${shop.mail.host}") is fine for one setting. It does not scale to ten, because each field repeats the key as a string that the compiler cannot check, the type conversion is implicit, and there is no single place that shows what the application can be configured with. A @ConfigurationProperties class gives the settings a name, a type and a home. The IDE completes the keys in application.yaml when the configuration processor is on the annotation processor path, and a rename of a field shows up as a compile error where it is used.

The class is also the right unit to pass around. A service that needs the timeout takes a MailProperties in its constructor, and a test builds one with new MailProperties("localhost", 25, Duration.ofSeconds(1)) with no Spring involved. A service that uses @Value needs a container or reflection in the test, which is exactly the friction that makes people skip the test.

Immutable records and defaults

Constructor binding with a record produces an immutable object, which is what you want from configuration: it cannot be changed after startup by a stray setter. Provide defaults with @DefaultValue on the component, so a setting that most deployments never touch needs no entry in any file. Document each property with Javadoc on the record component, and the processor copies the text into the metadata, so an operator hovering over the key in the IDE reads your explanation.

Fail on typos in the configuration file

A misspelled key, shop.mial.host, binds nothing, and the application starts with the default. Set ignoreUnknownFields = false on the annotation for a class where that matters, and Boot rejects a key under the prefix that matches no property. It is stricter than most teams want for every class, so use it for the settings where a silent default is dangerous, such as a payment endpoint or a security flag.

Where this does not apply

A single value used in one place can stay a @Value. See the Boot reference on type-safe configuration and the binding rules.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.