Sub topic 8
Failing fast with validated properties
This chapter assumes you can already bind a group of properties to a @ConfigurationProperties class, as the previous chapter showed. It also assumes you know how property sources are ordered. Here you add validation, so a bad value stops the application at startup instead of failing later in production.
Why validate configuration
A wrong configuration value often does no harm until the code that uses it runs. A mail port of 0 or a blank host may only show up when the first email is sent, possibly hours after deployment. By then the cause is far from the symptom.
Spring Boot can check values while it binds them. If a constraint fails, the application context does not start. This is called failing fast. The process exits with a clear message, a deployment pipeline sees the failure, and the old version keeps running.
Add the validation dependency
Boot does not include a validator by default. Add the validation starter, which brings in the Jakarta Bean Validation API and Hibernate Validator.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>With Gradle, the equivalent is implementation 'org.springframework.boot:spring-boot-starter-validation'.
Annotate the properties class
Put @Validated on the class and constraint annotations on the fields or record components. The class below is the one from the earlier chapters, now with constraints.
import jakarta.validation.constraints.Email;
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 = "app.mail")
public record MailProperties(
@NotBlank String host,
@Min(1) @Max(65535) int port,
@Email String sender,
@DefaultValue("3") int retryAttempts) {
}Register it with @ConfigurationPropertiesScan or @EnableConfigurationProperties(MailProperties.class). Without @Validated, the constraint annotations are ignored. Boot does not warn you.
When validation runs
Validation happens during binding, before the bean is handed to the rest of the application. The order matters because it explains which error you see.
Conversion comes first. If app.mail.port=abc, Boot cannot turn the text into an int, so you get a conversion error and no constraint is checked. Constraints only run on values that converted successfully.
What a failure looks like
Suppose the active sources set app.mail.port=70000. The application stops with output similar to this:
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.example.MailProperties failed:
Property: app.mail.port
Value: "70000"
Origin: "app.mail.port" from property source "commandLineArgs"
Reason: must be less than or equal to 65535
Action:
Update your application's configurationThree parts of this message help you debug. Property is the full key, Value is what was bound, and Origin names the source that supplied it. If the bad value comes from an environment variable on one server, Origin points straight at it.
Constraint behavior to know
Each constraint has its own rule for missing values. These rules cause most surprises.
| Constraint | Missing (null) value | Blank string | Typical use |
|---|---|---|---|
| `@NotNull` | fails | passes | any required object |
| `@NotBlank` | fails | fails | required text such as a host |
| `@NotEmpty` | fails | fails | required text or collections |
| `@Email` | passes | passes | format check on optional text |
| `@Min` / `@Max` | passes for wrapper types | not applicable | numeric ranges |
@Email accepts null and the empty string, so it does not make sender required. Combine it with @NotBlank if the value must be present.
A primitive int can never be null. If app.mail.port is missing, Boot binds the default 0, and @Min(1) then reports the problem. The message says the value must be at least 1, not that the property is missing. The Origin line will be absent in that case. If you want a clearer message, use Integer with @NotNull.
Nested properties need @Valid
Boot validates the top-level class. It does not descend into nested objects unless you mark them with @Valid. Without it, constraints on the nested class are silently skipped.
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "app.client")
public record ClientProperties(
@NotBlank String baseUrl,
@Valid @DefaultValue Limits limits) {
public record Limits(
@Min(1) @DefaultValue("10") int maxConnections,
@NotNull @DefaultValue("2s") Duration connectTimeout) {
}
}@DefaultValue on the limits component makes Boot create a Limits object even when no app.client.limits.* keys exist. Its own defaults then apply. If you leave @Valid off, app.client.limits.max-connections=0 would pass without complaint.
Validation and profiles
Validation runs against the final merged values, after profile files and overrides are applied. In the multi-document application.yaml from earlier chapters, the prod profile overrides app.mail.host and app.mail.port. The constraints check those production values when prod is active, and the local defaults otherwise.
This means a value that is valid in development can fail in production, and the reverse. Test with the profiles you deploy. A mistyped APP_MAIL_PORT environment variable on the server is caught at startup, but only when that variable is present.
Testing that bad values are rejected
You can check the constraints without starting a whole application. ApplicationContextRunner builds a small context with properties you supply.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Configuration;
class MailPropertiesValidationTest {
@Configuration
@EnableConfigurationProperties(MailProperties.class)
static class TestConfig {
}
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(TestConfig.class);
@Test
void rejectsPortOutOfRange() {
runner.withPropertyValues("app.mail.host=localhost", "app.mail.port=70000")
.run(context -> assertThat(context).getFailure()
.hasStackTraceContaining("app.mail"));
}
@Test
void acceptsValidValues() {
runner.withPropertyValues("app.mail.host=localhost", "app.mail.port=1025")
.run(context -> assertThat(context).hasNotFailed());
}
}Each test starts and discards a tiny context, so these run quickly. Add a case for every constraint you care about. Doing so also documents what the application requires.
Common mistakes
- Forgetting
@Validated. The constraints compile and do nothing. - Missing the validation starter. The
jakarta.validationannotations will not compile, or no validator runs. - Expecting
@Emailor@Minto reject a missing value. Add@NotNullor@NotBlank. - Forgetting
@Validon nested properties. - Using a primitive type and getting a confusing "must be at least 1" message for an absent property.
- Checking only the default profile. Production overrides can break constraints that local values satisfy.
Exercise
A team adds @Min(1) @Max(65535) int port to a record annotated with @ConfigurationProperties(prefix = "app.mail") and sets app.mail.port=70000. The application still starts normally. Give two likely causes and say how to confirm each.
Show answer
First, the record is missing @Validated, so Boot ignores the constraints. Check the class for the annotation. Second, spring-boot-starter-validation is not on the classpath, so no validator runs (or the Jakarta validation annotations would not compile). Check the dependency tree. A third possibility is that a higher-precedence source overrides the port with a valid value, which you can find by looking at the Origin of the bound value. After fixing either cause, starting with app.mail.port=70000 should stop with "Binding to target ... failed" and "must be less than or equal to 65535".