Video in progress
How do you make @ConfigurationProperties immutable, and how do you make the application stop at startup on a bad setting?
You write the class as a record (or a class with a constructor); in Boot 3 constructor binding is automatic. You add @Validated and put constraints like @NotBlank and @Min on the fields; if a value is wrong, the context doesn't start.
📖 Answer
@ConfigurationProperties(prefix = "payment.click")
@Validated
public record ClickProperties(
@NotBlank String merchantId,
@NotNull URI baseUrl,
@DefaultValue("5s") Duration timeout,
@Min(1) @Max(10) @DefaultValue("3") int maxRetries) {
}
@SpringBootApplication
@ConfigurationPropertiesScan
class App { }
payment:
click:
merchant-id: ${CLICK_MERCHANT_ID}
base-url: https://api.example.uz
timeout: 3s
What this gives you:
- Immutability: there are no setters, so no code can change
timeoutat runtime and confuse other services. - Fail fast: if
CLICK_MERCHANT_IDisn't provided, the application stops at startup with the messageBinding validation errors on payment.click. That's far better than an NPE that shows up at the first payment. - Types:
Duration("3s", "500ms"),DataSize("10MB"),URIand enums are converted automatically.
In Boot 2.x you needed @ConstructorBinding for constructor binding; in Boot 3 it isn't needed when there's a single constructor, and with several you put it on the one you want.
If you add the spring-boot-configuration-processor dependency, the IDE shows autocompletion and documentation in YAML, which makes it much easier for the team to find the settings.
Sign up to mark studied questions and save your progress.