TExcelTAD
Home › Spring Boot › @ConfigurationProperties

@ConfigurationProperties

@Value injects one property at a time as a loosely typed string expression. For a group of related settings, @ConfigurationProperties is better: it binds every key under a prefix to a typed Java object — with nested objects, lists, maps, durations, data sizes, defaults and validation. Combined with Java records, it is the cleanest way to model configuration.

Binding to a record

yaml
tasks:
  page-size: 25
  max-title-length: 120
  reminder-delay: 30m
  allowed-tags: [work, home, urgent]
  mail:
    from: noreply@tasks.example.com
    enabled: true
java
package com.example.tasks.config;

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 = "tasks")
public record TaskProperties(
        @DefaultValue("20") int pageSize,
        @DefaultValue("200") int maxTitleLength,
        @DefaultValue("1h") Duration reminderDelay,
        List<String> allowedTags,
        Mail mail) {

    public record Mail(String from, @DefaultValue("false") boolean enabled) {}
}

Enable it once, then inject it anywhere like any other bean:

java
@SpringBootApplication
@ConfigurationPropertiesScan          // finds all @ConfigurationProperties classes
public class TasksApplication { ... }

@Service
class ReminderService {
    private final TaskProperties props;
    ReminderService(TaskProperties props) { this.props = props; }

    String describe() {
        return "Reminders after " + props.reminderDelay().toMinutes() + " min, mail from " + props.mail().from();
    }
}

Records use constructor binding automatically: properties are passed to the canonical constructor, and the resulting object is immutable.

Kebab-case in config Java component
page-size pageSize
max-title-length maxTitleLength
mail.from mail().from()

How binding converts values

Spring converts each string into the target type. Duration accepts 30m, 10s, 2h, 500ms or ISO-8601 (PT30M); DataSize accepts 10MB. This program imitates the binder for a few types:

java · try it yourself
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

record Mail(String from, boolean enabled) {}
record TaskProperties(int pageSize, Duration reminderDelay, List<String> allowedTags, Mail mail) {}

class Binder {
    static Duration duration(String s) {
        if (s.startsWith("PT")) return Duration.parse(s);
        long n = Long.parseLong(s.replaceAll("[a-z]+
quot;, "")); String unit = s.replaceAll("^[0-9]+", ""); return switch (unit) { case "ms" -> Duration.ofMillis(n); case "s" -> Duration.ofSeconds(n); case "m" -> Duration.ofMinutes(n); case "h" -> Duration.ofHours(n); case "d" -> Duration.ofDays(n); default -> throw new IllegalArgumentException("bad duration " + s); }; } static TaskProperties bind(Map<String, String> p) { return new TaskProperties( Integer.parseInt(p.getOrDefault("tasks.page-size", "20")), duration(p.getOrDefault("tasks.reminder-delay", "1h")), Arrays.stream(p.getOrDefault("tasks.allowed-tags", "").split(",")) .map(String::strip).filter(t -> !t.isEmpty()).toList(), new Mail(p.get("tasks.mail.from"), Boolean.parseBoolean(p.getOrDefault("tasks.mail.enabled", "false")))); } } class Main { public static void main(String[] args) { Map<String, String> source = Map.of( "tasks.page-size", "25", "tasks.reminder-delay", "30m", "tasks.allowed-tags", "work, home, urgent", "tasks.mail.from", "noreply@tasks.example.com"); TaskProperties props = Binder.bind(source); System.out.println(props); System.out.println("Delay in seconds: " + props.reminderDelay().toSeconds()); System.out.println("Defaults: " + Binder.bind(Map.of())); } }
TaskProperties[pageSize=25, reminderDelay=PT30M, allowedTags=[work, home, urgent], mail=Mail[from=noreply@tasks.example.com, enabled=false]]
Delay in seconds: 1800
Defaults: TaskProperties[pageSize=20, reminderDelay=PT1H, allowedTags=[], mail=Mail[from=null, enabled=false]]

Validating configuration

Add spring-boot-starter-validation, annotate the class with @Validated and use Jakarta constraints. Invalid configuration then stops the application at startup — far better than a surprise in production.

java
@Validated
@ConfigurationProperties(prefix = "tasks")
public record TaskProperties(
        @Min(1) @Max(100) @DefaultValue("20") int pageSize,
        @NotEmpty List<String> allowedTags,
        @Valid Mail mail) {

    public record Mail(@Email String from, boolean enabled) {}
}
bash · try it yourself
./mvnw spring-boot:run -Dspring-boot.run.arguments=--tasks.page-size=500
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.example.tasks.config.TaskProperties failed:

    Property: tasks.pageSize
    Value: "500"
    Origin: "tasks.page-size" from property source "commandLineArgs"
    Reason: must be less than or equal to 100


Action:

Update your application's configuration

The report even tells you where the bad value came from (commandLineArgs), which is invaluable when configuration is spread over files, environment variables and arguments.

IDE support: configuration metadata

Add the annotation processor and your IDE autocompletes and documents your own properties, just like Boot's:

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

Javadoc comments on record components become the property descriptions.

@Value vs. @ConfigurationProperties

@Value @ConfigurationProperties
Granularity single value a whole group under a prefix
Type safety per parameter full typed object, nested types
Relaxed binding limited full (page-size, pageSize, PAGE_SIZE)
Validation no yes, with @Validated
IDE metadata no yes, with the processor
SpEL expressions yes (#{...}) no

Tip: Treat @ConfigurationProperties records as the single, documented contract between your application and its operators. Everything an ops team can tune should appear there.

Test yourself

How does a record annotated with @ConfigurationProperties receive its values?

  1. Setter methods
  2. Field reflection
  3. Constructor binding through the canonical constructor
  4. It cannot; records are not supported

Which YAML key binds to the record component maxTitleLength under prefix tasks?

  1. tasks.MaxTitleLength
  2. tasks.max-title-length
  3. tasks_max_title_length only
  4. maxTitleLength without prefix

What happens at startup when @Validated configuration properties violate a constraint?

  1. The value is silently clamped
  2. A warning is logged and the app continues
  3. Startup fails with a binding report naming the property and its origin
  4. The default value is used