Sub topic 6
Tuning Defaults with Properties and @ConfigurationProperties
An auto-configuration decides which beans exist. Properties decide how those beans behave. This chapter covers how Boot turns values from application.properties, environment variables, and the command line into typed Java objects, and how an auto-configuration uses them to expose safe defaults.
This chapter assumes you can create and run a Spring Boot application, you know @Configuration and @Bean, and you have seen @ConditionalOnMissingBean from the previous chapter.
Why properties are the first tuning knob
Overriding a bean (covered in the next chapter) replaces a whole component. Often you only want to change one value, such as a timeout, a port, or a greeting. Properties let users do that without writing Java. A well-designed auto-configuration therefore:
- Ships sensible defaults, so it works with zero configuration.
- Reads every tunable value from a properties class.
- Lets users change a value from any property source, with no code change.
Where property values come from
Boot collects values from many property sources into one Environment. When the same key appears in several places, the source with higher precedence wins. This table is a simplified view, from highest to lowest:
| Precedence | Source | Example |
|---|---|---|
| 1 | Command-line arguments | `--greeting.message=Hi` |
| 2 | `SPRING_APPLICATION_JSON` | `{"greeting":{"message":"Hi"}}` |
| 3 | OS environment variables | `GREETING_MESSAGE=Hi` |
| 4 | Profile-specific files | `application-prod.properties` |
| 5 | Default config files | `application.properties`, `application.yml` |
| 6 | `@PropertySource` and defaults | `SpringApplication.setDefaultProperties` |
Test annotations such as @SpringBootTest(properties = ...) sit above the config files, and the full list in the Boot reference documentation has more entries. The practical rule is that the more specific and more temporary a source is, the higher it ranks. A command-line flag beats a file, and a profile file beats the general file.
Binding with @ConfigurationProperties
You could read each value with @Value("${greeting.message}"). That works for one or two values, but it scatters key names across your code, has no defaults in one place, and does not group related settings. @ConfigurationProperties binds a whole prefix to one class.
This is the class from our running example:
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 source defines greeting.message, the field keeps that value. If one does, the Binder calls setMessage. A user can now write this:
# application.properties
greeting.message=WelcomeWith JavaBean binding like this, the class needs a getter and a setter for every property. A missing setter is a common cause of a value that is silently never applied.
Relaxed binding
Property names do not have to match the Java field name exactly. Boot's Binder treats these forms of the same key as equal:
| Where the value is written | Form for field `maxLength` |
|---|---|
| `.properties` and `.yml` (recommended) | `greeting.max-length` |
| `.properties` and `.yml` (also accepted) | `greeting.maxLength`, `greeting.max_length` |
| Environment variable | `GREETING_MAXLENGTH` |
Use kebab-case (max-length) in files, because it is the canonical form and the only one that @ConditionalOnProperty and other lookups match reliably. In environment variables, use upper case, replace dots with underscores, and drop the dashes.
Registering the properties class
Declaring @ConfigurationProperties on a class does not make it a bean. Something must register it. You have three options:
@EnableConfigurationProperties(GreetingProperties.class)on a configuration class. Use this in auto-configurations, because it registers the class without depending on component scanning.@ConfigurationPropertiesScanon your application class. It scans for annotated classes, which suits an application with many of them.@Componenton the properties class. It works, but it ties the class to component scanning, so avoid it in libraries.
The auto-configuration from the spine uses the first option:
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}The GreetingProperties bean is injected into the @Bean method, so the service receives whatever value the Binder produced.
Constructor binding and records
Mutable setters are not required. Since Spring Boot 3, a properties class with a single parameterized constructor binds through that constructor. A record is the shortest form:
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
@ConfigurationProperties(prefix = "greeting")
public record GreetingProperties(
@DefaultValue("Hello") String message,
@DefaultValue("5s") Duration timeout,
@DefaultValue("false") boolean shout) {
}@DefaultValue supplies the default when no source defines the property. The object is immutable, so nothing can change a setting after startup. If a class has several constructors, mark the one to use with @ConstructorBinding. For the record form, call properties.message() instead of getMessage().
Type conversion
The Binder converts text to the target type. Beyond strings and numbers, it handles types that make configuration readable:
Duration:5s,200ms,2m, or ISO-8601 such asPT30S.DataSize:10MB,512KB.- Enums: matched case-insensitively and with relaxed names.
- Lists and sets:
greeting.names=Ann,Bobor indexed keysgreeting.names[0]=Ann. - Maps:
greeting.labels.en=Helloandgreeting.labels.fr=Bonjour. - Nested objects:
greeting.retry.max-attempts=3binds to a nested class with amaxAttemptsfield.
If a value cannot be converted, for example greeting.timeout=soon, startup fails with a BindException that names the property and the source file. That failure is intentional, because it is better than running with a wrong value.
Validating values
Add @Validated and Jakarta Bean Validation constraints to reject bad values at startup. You need spring-boot-starter-validation on the classpath.
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "greeting")
public class GreetingProperties {
@NotBlank
private String message = "Hello";
@Min(1)
private int maxLength = 80;
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public int getMaxLength() { return maxLength; }
public void setMaxLength(int maxLength) { this.maxLength = maxLength; }
}Setting greeting.message= (blank) or greeting.max-length=0 now stops the application with a message that lists each violated constraint. For nested objects, add @Valid on the nested field, or its constraints are skipped.
Toggling an auto-configuration with a property
Properties can also decide whether a bean exists at all. @ConditionalOnProperty reads the same Environment:
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true)
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}matchIfMissing = true makes the feature on by default, so users opt out with greeting.enabled=false. Without matchIfMissing, a missing property counts as a non-match and the bean is skipped.
Helping users with configuration metadata
Users editing application.properties get autocomplete and documentation in their IDE if your library ships metadata. Add the processor as an annotation-processor dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>At compile time it generates META-INF/spring-configuration-metadata.json from your @ConfigurationProperties classes. It reads Javadoc on fields as the property description, so write a short comment on each field. In Gradle, use annotationProcessor for this dependency.
Common errors
- The value is ignored and no error appears. By default, unknown properties are not an error. A typo such as
greting.messageis silently dropped. Check the key against the prefix, and consider the IDE metadata above to catch typos. - The properties bean does not exist. The class lacks
@EnableConfigurationProperties,@ConfigurationPropertiesScan, or@Component, so injection fails withNoSuchBeanDefinitionException. - A JavaBean property stays at its default. The class has no setter, or the setter's name does not match the field.
- An environment variable is not picked up. The name keeps its dashes or is lower case. Use
GREETING_MAXLENGTH. - Validation annotations have no effect.
@Validatedis missing, or no validator is on the classpath. - A nested object is not validated. The nested field needs
@Valid.
Summary of the working model
- Property sources fill the
Environment, and higher-precedence sources win. - The Binder maps keys with a given prefix onto a properties class, with relaxed naming and type conversion.
- Defaults live in the class, as field initializers or
@DefaultValue. @EnableConfigurationPropertiesmakes the class a bean that the auto-configuration injects.@Validatedmakes bad values fail at startup instead of at run time.
Exercise
A user sets the environment variable GREETING_MESSAGE=Hola, and application.properties contains greeting.message=Welcome. Your GreetingProperties class is registered with @EnableConfigurationProperties and has a getter and setter for message. What does greetingService.greet("Ann") return, and what do you change if the user wants the file to win instead?
Show answer
It returns "Hola, Ann!". OS environment variables rank above application.properties, so the Binder sets message to "Hola". To make the file value win, remove the environment variable. You can also start the application with --greeting.message=Welcome, because command-line arguments rank above environment variables.
Exercise
You add a field maxLength with @Min(1) to a properties class bound to the prefix greeting, but greeting.max-length=0 does not stop the application. List two causes to check.
Show answer
First, the class is missing @Validated, so no constraints are checked. Second, no validator is on the classpath, because spring-boot-starter-validation is not a dependency. If the constraint is on a field inside a nested object, a missing @Valid on that nested field is a third cause.