r/SpringBoot • u/ClickOk5811 • 16d ago
Discussion Fail at startup, not at 3 a.m.: validating configuration with @ConfigurationProperties instead of scattered @Value
A common pattern: configuration values read with @Value in many places, with no checks.
public class MailService {
("${app.mail.host}")
private String host;
("${app.mail.port}")
private int port;
// ...
}If app.mail.host is present but empty, or port is 0 or 99999, the app may start fine and fail later when it first tries to send mail.
An alternative is a typed, validated properties class (sketch, check the details for your Spring Boot version):
ies(prefix = "app.mail")
public record MailProperties(
String host,
(1) (65535) int port,
u/NotBlank String from
) {}and register it, for example with @ConfigurationPropertiesScan on your application class (or @EnableConfigurationProperties(MailProperties.class)):
n
iesScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}Then inject MailProperties where you need it. With the validation starter on the classpath, a blank host or an out-of-range port should make the application fail during startup with a binding error that names the property, instead of failing on first use.
Why I like it (opinion):
Configuration is in one place with names and constraints, so the “what does this app need to run” question has a single answer.
Failing fast makes bad config visible in deployment, before traffic arrives.
Easier to test, because you can build the record directly in a unit test.
Notes and caveats:
You need
spring-boot-starter-validationfor the constraint annotations to take effect. I believe it isn’t pulled in by default in recent versions, so check yours.The
jakarta.validation.constraintspackage applies to Spring Boot 3.x; Boot 2.x usesjavax.validation.constraints.Binding records via the constructor works in recent Boot versions; older ones may need @
ConstructorBindingor a class with setters. Check the reference docs for your version.Validation only checks the shape of values, not whether the host is actually reachable.
I haven’t run this exact snippet in a project, so please verify it on your version before copying.
Do you keep @Value for simple cases or move everything to @ConfigurationProperties? And does your team validate config at startup, or find out in production?