Sub topic 7
Binding groups of properties with @ConfigurationProperties
This chapter assumes you can read YAML and .properties files. It also assumes you have a Spring Boot application, understand constructor injection, and know Java records. Relaxed binding, @Value, and the property precedence order were covered in earlier chapters. Validation has its own chapter, so it appears here only as a pointer.
Why bind groups instead of single values
@Value("${app.mail.host}") reads one property at a time. Once a feature has five or six settings, the keys are scattered across constructors. Each key is a string that the compiler cannot check, and each default is written wherever the value is used.
@ConfigurationProperties solves this by binding every property under a prefix to one typed object. You get one place to see all settings of a feature, compile-time field names, type conversion, and nested structure.
| Concern | `@Value` | `@ConfigurationProperties` |
|---|---|---|
| Scope | One property per injection point | A whole prefix per class |
| Relaxed binding | Limited. Use the canonical kebab-case key. | Full |
| Lists, maps, nested objects | Awkward | Natural |
| IDE metadata | None | Generated from the class |
| SpEL expressions | Supported | Not supported |
The properties you will bind
This chapter uses the application.yaml from the profiles examples. Defaults are for local development, and the prod document overrides only the host and port.
app:
mail:
host: localhost
port: 1025
sender: [email protected]
retry-attempts: 3
---
spring:
config:
activate:
on-profile: prod
app:
mail:
host: smtp.example.com
port: 587Binding to a record
A record is the simplest way to declare a properties class. It is immutable and has one constructor, and Spring Boot binds through that constructor.
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
@ConfigurationProperties(prefix = "app.mail")
public record MailProperties(
String host,
int port,
String sender,
@DefaultValue("3") int retryAttempts) {
}The binder takes each constructor parameter name, converts it to the canonical property name, and looks it up. The parameter retryAttempts matches the key app.mail.retry-attempts. This is relaxed binding at work, so you never write the kebab-case name in Java.
@DefaultValue("3") supplies a value when the property is absent. Without it, a missing int binds as 0. A missing object type such as String binds as null.
Registering the class as a bean
Annotating the record is not enough. Spring must also be told to create it. There are two supported ways.
The first is to scan for annotated classes:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}@ConfigurationPropertiesScan registers every @ConfigurationProperties class in the application's packages. The second way is explicit registration, which suits libraries and small apps:
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(MailProperties.class)
class MailConfig {
}The result is a normal bean, so you inject it like any other:
import org.springframework.stereotype.Service;
@Service
class MailService {
private final MailProperties mail;
MailService(MailProperties mail) {
this.mail = mail;
}
String describe() {
return mail.host() + ":" + mail.port() + " as " + mail.sender();
}
}How the binder works
The binder runs against the merged Environment, so precedence has already been resolved. A --app.mail.port=2525 argument wins over the file value without any extra code in your class. Because the binder uses relaxed matching, APP_MAIL_RETRYATTEMPTS=5 in the environment also reaches the same record component.
Nested objects, lists, maps and durations
Real configuration is rarely flat. Records nest naturally, and the binder knows how to convert common types.
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
@ConfigurationProperties(prefix = "app.client")
public record ClientProperties(
String baseUrl,
@DefaultValue("5s") Duration timeout,
@DefaultValue Pool pool,
List<String> allowedHosts,
Map<String, String> headers) {
public record Pool(@DefaultValue("10") int maxSize,
@DefaultValue("30s") Duration idleTimeout) {
}
}app:
client:
base-url: https://api.example.com
timeout: 2s
pool:
max-size: 20
allowed-hosts:
- api.example.com
- backup.example.com
headers:
x-mailer: demo
x-trace: enabledPoints to notice:
Durationaccepts values such as500ms,2s,5m, or ISO-8601 likePT2S. A bare number uses milliseconds unless you add@DurationUnit.- A bare
@DefaultValueon a nested record means "create the nested object even when none of its keys are set". Without it,poolwould benullwhen the YAML has nopoolsection. - Lists bind from YAML sequences, from indexed properties such as
app.client.allowed-hosts[0], or from a comma-separated string. - Map keys are kept as written. In
.propertiesfiles, keys containing characters other than letters, digits, and-need brackets, as inapp.client.headers[x.trace]=on. DataSize(10MB) andPeriod(2d) are also supported.
JavaBean binding
Before records, properties classes were mutable beans with getters and setters. This style still works and is the only choice if you need a mutable object. It needs a no-argument constructor and setters, and the class must be registered as a bean through one of the two methods above. A class annotated with @Component is also valid in this style.
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app.mail")
public class MailSettings {
private String host = "localhost";
private int port = 25;
public String getHost() { return host; }
public void setHost(String host) { this.host = host; }
public int getPort() { return port; }
public void setPort(int port) { this.port = port; }
}Defaults here are field initializers. If a class has several constructors, mark the one to use with @ConstructorBinding to get constructor binding. With a single constructor, Boot picks constructor binding for records automatically.
Failure behavior and what the binder ignores
- Unknown keys are ignored. A typo such as
app.mail.hotsdoes not fail. The field just keeps its default. SetignoreUnknownFields = falseon the annotation if you want typos to fail. - Type mismatches fail startup.
app.mail.port=abcraises aBindException, and the message names the property, the value, and the origin file and line. - Missing values are not errors by default. To require them, add validation, which is the next chapter.
Exercise
A record ClientProperties has a component Pool pool with no @DefaultValue, and application.yaml has no app.client.pool section. What does properties.pool() return, and how do you change that so properties.pool().maxSize() returns 10?
Show answer
It returns null, because nothing under app.client.pool is present, so the binder creates no nested object. Annotate the component with a bare @DefaultValue so the nested record is always created, and put @DefaultValue("10") on maxSize. The nested object is then built with its defaults even when no keys exist.
Exercise
You start the application with APP_MAIL_RETRYATTEMPTS=5 set and retry-attempts: 3 in application.yaml. What value does MailProperties.retryAttempts() have, and why?
Show answer
5. The environment variable is a property source with higher precedence than the packaged file. Relaxed binding maps APP_MAIL_RETRYATTEMPTS to the canonical name app.mail.retry-attempts, which is what the record component retryAttempts is matched against.