Sub topic 9
Typed settings for your auto-configuration
An auto-configuration that hard-codes its values is hard to adapt. Spring Boot's answer is @ConfigurationProperties, which binds groups of external settings to a typed Java object. This chapter assumes you know application.properties, @Bean methods, and the GreetingAutoConfiguration from the previous chapters. Here you will extend it with a properties class that is validated, documented for IDEs, and tested.
Why a properties class instead of @Value
You can inject a single setting with @Value("${greeting.message}"). That works for one value, but it scales badly in a library:
- Each
@Valuerepeats the key string, so a typo only shows up at runtime. - There is no grouping, no nested structure, and no IDE metadata.
- Relaxed binding (see below) is limited.
- Validation and type conversion are harder to apply uniformly.
A @ConfigurationProperties class gathers all settings under one prefix. Spring Boot's Binder reads them from the Environment and converts them to the target types.
The basic version
The properties class from the spine uses setter binding:
package com.example.greeting;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "greeting")
public class GreetingProperties {
private String message = "Hello";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}The field initializer "Hello" is the default. If no greeting.message exists in any property source, the binder leaves the field untouched. With JavaBean binding, the binder needs a no-argument constructor and a setter for each property. A missing setter is the most common reason a value silently stays at its default.
The annotation alone does not create a bean. Something must register the class. In an auto-configuration, use @EnableConfigurationProperties on the configuration class:
@AutoConfiguration
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration { /* ... */ }This registers GreetingProperties as a bean and binds it. Its bean name is greeting-com.example.greeting.GreetingProperties (prefix plus fully qualified class name), which avoids clashes if two libraries use the same simple class name.
Don't use @ConfigurationPropertiesScan or @Component on the properties class in a library. Scanning is driven by the user's application package, so it would not find a class in your library, and a @Component would only register if the user's component scan happened to cover your package.
Constructor binding and records
Mutable beans with setters are optional. Since Spring Boot 3, a @ConfigurationProperties class with a single parameterized constructor uses constructor binding automatically. Records fit this model well and give you immutable settings:
package com.example.greeting;
import java.time.Duration;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "greeting")
public record GreetingProperties(
@DefaultValue("Hello") @NotBlank String message,
@DefaultValue("3") @Min(1) @Max(10) int maxRetries,
@DefaultValue("2s") Duration timeout) {
}Points to note:
@DefaultValuesupplies a default when the property is absent. Without it, a missingintbecomes0and a missing object becomesnull.- With multiple constructors, mark the one to use with
@ConstructorBinding(fromorg.springframework.boot.context.properties). - You do not need getters or setters, so you cannot forget one.
- A nested record or class parameter is bound as a sub-group, for example
greeting.retry.delay. Add@DefaultValueon the nested parameter if you want a non-null instance when no nested property is set.
The constructor in GreetingAutoConfiguration must change to match: new GreetingService(properties.message()).
Type conversion
The binder converts strings to the declared type. Common conversions include:
| Declared type | Example property value | Result |
|---|---|---|
| `Duration` | `2s`, `500ms`, `PT1M` | A `Duration` of that length |
| `DataSize` | `10MB`, `512KB` | A `DataSize` in bytes |
| `List<String>` | `a,b,c` or `list[0]=a` | A list with three elements |
| `enum` | `warn` or `WARN` | The matching constant, case-insensitive |
| `Map<String,String>` | `greeting.labels.en=Hello` | A map entry `en` to `Hello` |
A value that cannot be converted, such as greeting.max-retries=abc, fails at startup with a BindException that names the property and the origin file and line. That is far better than a NumberFormatException deep in your code.
Relaxed binding
The binder accepts several spellings of one logical property. All of these bind to maxRetries:
greeting.max-retries=5
greeting.maxRetries=5
greeting.max_retries=5The environment variable form is GREETING_MAXRETRIES or GREETING_MAX_RETRIES. Use the lowercase kebab-case form in application.properties, in documentation, and in the prefix attribute. The prefix must be kebab-case. A prefix such as "myGreeting" is rejected when the application starts.
Validation
Add @Validated to the class and Jakarta Bean Validation annotations to the fields or parameters. The binder validates after binding, and an invalid value stops startup:
Binding to target ... failed:
Property: greeting.max-retries
Value: "50"
Reason: must be less than or equal to 10Validation only happens if a Bean Validation provider such as Hibernate Validator is on the classpath. In a library, declare it as an optional or documented dependency, or tell users to add spring-boot-starter-validation. Without a provider, the constraints are silently not enforced, so test this explicitly (see below).
Properties and conditions are separate
@ConditionalOnProperty and @ConfigurationProperties both read the Environment, but they do not interact. The condition runs while Spring is still deciding which configuration classes to process. At that point the GreetingProperties bean does not exist yet. So the condition on greeting.enabled reads the raw property, not a field of your properties class.
If you want greeting.enabled to appear in IDE completion, add an enabled component to the record or define it in additional metadata. Keep in mind that the property bound to the object has no effect on the condition. The condition still reads the raw property.
Metadata for IDEs
Add the configuration processor so users get completion and documentation for greeting.* in their IDE:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>In Gradle, use annotationProcessor "org.springframework.boot:spring-boot-configuration-processor". At compile time, the processor writes META-INF/spring-configuration-metadata.json, including defaults and Javadoc from your fields. Write a short Javadoc comment on each property, since it becomes the description users see.
Testing the binding
ApplicationContextRunner can check both binding and validation. This test assumes Hibernate Validator is on the test classpath:
package com.example.greeting;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class GreetingPropertiesTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));
@Test
void usesDefaults() {
this.contextRunner.run(context -> {
GreetingProperties properties = context.getBean(GreetingProperties.class);
assertThat(properties.message()).isEqualTo("Hello");
assertThat(properties.timeout()).isEqualTo(Duration.ofSeconds(2));
});
}
@Test
void bindsRelaxedNames() {
this.contextRunner.withPropertyValues("greeting.max-retries=5", "greeting.timeout=500ms")
.run(context -> {
GreetingProperties properties = context.getBean(GreetingProperties.class);
assertThat(properties.maxRetries()).isEqualTo(5);
assertThat(properties.timeout()).isEqualTo(Duration.ofMillis(500));
});
}
@Test
void rejectsOutOfRangeValue() {
this.contextRunner.withPropertyValues("greeting.max-retries=50")
.run(context -> assertThat(context).hasFailed());
}
}Common errors
- Value stays at the default. For setter binding, the setter is missing or has the wrong name. For constructor binding, the parameter name does not match the property.
NoSuchBeanDefinitionExceptionfor the properties class. The class was never registered. Add@EnableConfigurationProperties.- Constraints have no effect.
@Validatedis missing, or no Bean Validation provider is on the classpath. - Startup fails with an invalid prefix. The prefix is not lowercase kebab-case.
- A
nullnested object. Nothing was bound under that sub-prefix, and the nested parameter has no@DefaultValue.
Exercise
Your properties class has private int maxRetries; with a getter but no setter, and you set greeting.max-retries=5. The application starts, but getMaxRetries() returns 0. Give two ways to fix it.
Show answer
Add a setter setMaxRetries(int) so the JavaBean binder can write the value. Alternatively, convert the class to constructor binding (a record or a class with one parameterized constructor), where values are passed through the constructor and no setters are needed. Add @DefaultValue if you want a non-zero default.
Exercise
You add @Min(1) @Max(10) to maxRetries and set greeting.max-retries=50, but the application starts normally. Name two likely causes.
Show answer
Either the class lacks @Validated, or no Bean Validation provider (for example Hibernate Validator via spring-boot-starter-validation) is on the classpath. Both cause the constraint annotations to be ignored without an error.
Exercise
Why does @ConditionalOnProperty(prefix = "greeting", name = "enabled") still work even though GreetingProperties is registered as a bean in the same auto-configuration?
Show answer
The condition reads the raw greeting.enabled value from the Environment while configuration classes are being processed. It does not depend on the GreetingProperties bean, which does not exist at that point. Binding and condition evaluation are independent.