Configuration attribute verification enhancement highlights
Spring Boot 3.4 has comprehensively upgraded configuration verification support, and its core highlights include:
- supportA complete set of standard annotations (such as
@NotNull
、@Email
、@Pattern
wait) - Nested objects, collection elementsofIn-depth verificationsupport
- The verification failed in the startup phase.IDE friendly tips, quickly locate problems
- Automatically generate more completeMeta-information at development time(metadata)
It can be said that from ease of use to rigor, there has been a qualitative leap!
Basic usage examples
Define configuration classes
Take user configuration as an example:
package ; import ; import .*; import ; import ; import ; @Validated @ConfigurationProperties(prefix = "") public class UserProperties { @NotBlank(message = "Username cannot be empty") private String username; @Email(message = "The email format is incorrect") private String email; @Min(value = 18, message = "The age cannot be less than 18 years old") private Integer age; @Valid private Address address; @Size(min = 1, message = "At least one character is needed") private List<@NotBlank(message = "The role name cannot be empty") String> roles; // Address is a nested object, @Valid is required public static class Address { @NotBlank(message = "Cities cannot be empty") private String city; @Pattern(regexp = "\d{6}", message = "The zip code must be 6 digits") private String zipCode; // getter/setter public String getCity() { return city; } public void setCity(String city) { = city; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { = zipCode; } } // getter/setter public String getUsername() { return username; } public void setUsername(String username) { = username; } public String getEmail() { return email; } public void setEmail(String email) { = email; } public Integer getAge() { return age; } public void setAge(Integer age) { = age; } public Address getAddress() { return address; } public void setAddress(Address address) { = address; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { = roles; } }
Configuration
app: user: username: "Zhang San" email: "zhangsan@" age: 25 address: city: "Shanghai" zipCode: "200000" roles: - "admin" - "user"
Injection and use
Inject:
package ; import ; import ; @Service public class UserService { private final UserProperties userProperties; public UserService(UserProperties userProperties) { = userProperties; } public void printUserInfo() { ("username:" + ()); ("Mail:" + ()); } }
Depth verification of nested objects and collection elements
Note that it must be marked on nested objects@Valid
, the sub-attributes can be continued to be checked. Collection elements (such asList<String>
) Also supportedElement level verification annotation!
This makes the constraints of configuration classes more granular and secure.
Verification failed in the startup phase
If the configuration does not meet the requirements, such as missing fillusername
, erroneous email format, less than 18 years old, empty role list, etc.Spring Boot will directly report an error when it starts!
Example error log:
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target [Bindable@xxx type = ] failed:
Property:
Value:
Reason: The username cannot be empty
Property:
Value: not-an-email
Reason: The email format is incorrect
Very intuitive, can detect configuration problems as soon as possible, and avoid hidden dangers after the service is launched!
Meta-information enhancement during development
Cooperating with Spring Bootspring-boot-configuration-processor
Plugins can also automatically generate prompt completion information (IDE.yml
Configuration smart prompt)!
Configuration:
<dependency> <groupId></groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
After compilation, it will be generatedMETA-INF/
, for reference for IDE intelligent completion.
Things to note
-
@ConfigurationProperties
Must cooperate@Validated
- Nested object fields should be added
@Valid
- Collection element verification, need to add annotations on generics
- Use the Jakarta Validation standard annotation (Spring Boot uses Jakarta by default)
Extension: Error handling is more friendly (custom exception message format)
When the default startup verification fails, Spring Boot throwsBindValidationException
, although the information is complete, it is slightly messy. In order to make error prompts more professional and friendly, we can customize exception handling.
Define a friendly exception class
package ; /** * Custom configuration verification exception */ public class ConfigValidationException extends RuntimeException { public ConfigValidationException(String message) { super(message); } }
Writing an exception handler
passBeanFactoryPostProcessor
Verification errors in the unified intercept configuration phase:
package ; import ; import ; import ; import ; import ; import ; import ; @Configuration public class ConfigValidationExceptionHandler { @Bean public static BeanFactoryPostProcessor configurationPropertiesValidator() { return beanFactory -> { try { // Manually trigger bean initialization } catch (BeansException ex) { Throwable cause = (); if (cause instanceof BindValidationException bindValidationException) { String errorMessages = () .getAllErrors() .stream() .map(ObjectError::getDefaultMessage) .collect(("; ")); throw new ConfigValidationException("Configuration property verification failed:" + errorMessages); } throw ex; } }; } }
Logical explanation:
- Capture
BindValidationException
- Extract all verification failure information
- use
;
Spliced into simple and readable text - Throw ours
ConfigValidationException
Sample effects
For example, your configuration error is as follows:
app: user: username: "" email: "wrong" age: 15 address: city: "" zipCode: "12abc" roles: - ""
The error thrown at startup becomes:
Configuration attribute verification failed: The user name cannot be empty; the mailbox format is incorrect; the age cannot be less than 18 years old; the city cannot be empty; the zip code must be 6 digits; the role name cannot be empty
- Concentrated, concise and intuitive
- List all issues at once and quickly fix them
- Suitable for front-end and back-end colleagues to quickly understand
Summarize
Spring Boot 3.4 Configuration Properties Verification:
- More powerful verification capabilitiesCoverage depth verification, collection element verification
- The development experience is more extremeVerification is enabled, IDE smart prompt
- More elegant error handlingCustomizable exception format
- Improve overall code qualityAvoid configuration risks online
In actual projects, it is recommended to cooperateCustom exception mechanism, create a more professional and reliable configuration verification system!
This is the end of this article about the usage of the new SpringBoot configuration verification feature. For more related SpringBoot configuration verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!