Group Validation allows different verification rules to be applied to the same entity class in different scenarios. For example,Added dataandUpdate dataWhen , the verification rules for certain fields may need to be adjusted. The following are the specific implementation steps for group verification:
1. Define the packet interface
Create an empty tag interface (for grouping identification only):
// Verification grouping when addedpublic interface CreateGroup {} // Verification grouping during updatepublic interface UpdateGroup {}
2. Specify grouping in entity class
In the verification annotation of the field, passgroups
Attributes specify the group to which they belong:
public class User { @NotBlank(message = "User ID cannot be empty", groups = ) private String id; @NotBlank(message = "Username cannot be empty", groups = ) private String username; @Size(min = 6, max = 20, message = "The password length must be between 6 and 20 digits", groups = {, }) private String password; // Omit Getter and Setter}
-
id
Field: OnlyUpdateGroup
Verify under grouping (verify must be valid when updating). -
username
Field: OnlyCreateGroup
Verify in group (requires must be valid when added). -
password
Field: inCreateGroup
andUpdateGroup
Verify both in grouping (verify both when new and when updated).
3. Specify verification grouping in the Controller
Use on Controller method parameters@Validated
Note (note thatSpring's Notes, not@Valid
) and specify the grouping:
@RestController public class UserController { // Add new users (verify CreateGroup grouping) @PostMapping("/users") public String createUser(@Validated() @RequestBody User user) { return "User addition successful"; } // Update user (check UpdateGroup grouping) @PutMapping("/users/{id}") public String updateUser(@Validated() @RequestBody User user) { return "User update successful"; } }
4. Global exception handling
Group verification failure will be thrownConstraintViolationException
, it needs to be captured in the global exception handler:
@RestControllerAdvice public class GlobalExceptionHandler { @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler() public Map<String, Object> handleConstraintViolationException(ConstraintViolationException ex) { Map<String, String> errors = new HashMap<>(); ().forEach(violation -> { String field = ().toString(); String message = (); (field, message); }); return ( "code", HttpStatus.BAD_REQUEST.value(), "message", "Parameter verification failed", "data", errors ); } }
5. Test example
1. Add new users (trigger CreateGroup group verification)
ask:
POST /users Content-Type: application/json { "password": "12345" }
response:
{ "code": 400, "message": "Parameter verification failed", "data": { "username": "Username cannot be empty", "password": "The password length must be between 6 and 20 digits" } }
2. Update user (trigger UpdateGroup group verification)
ask:
PUT /users/123 Content-Type: application/json { "password": "12345" }
response:
{ "code": 400, "message": "Parameter verification failed", "data": { "id": "User ID cannot be empty", "password": "The password length must be between 6 and 20 digits" } }
6. Advanced usage of group verification
1. Multi-group combination verification
Can be@Validated
Specify multiple groups at the same time:
@Validated({, })
2. Default grouping
If the field is not specifiedgroups
The attribute is by defaultDefault
Group. Can be passed@Validated
ofvalue
The attribute also contains the default grouping:
@Validated(value = {, })
3. Inheriting grouping
The packet interface can inherit other interfaces to form a hierarchical relationship:
public interface AdvancedGroup extends CreateGroup {}
7. Group verification vs multiple DTOs
plan | advantage | shortcoming |
---|---|---|
Group verification | Avoid creating multiple similar DTOs and reduce redundant code | Entity classes may contain annotations for different scenarios |
Multiple DTOs | Single responsibilities and clear structure | Multiple DTO classes need to be maintained |
Summarize
Through group verification, you can flexibly control the verification rules in different scenarios, avoiding creating separate DTO classes for each scenario. Key steps:
Define the packet interface. Specify in the verification annotation of the entity class fieldgroups
. Use on Controller method parameters@Validated(grouping.class)
. Global CaptureConstraintViolationException
And return a custom error.
This is the article about the specific implementation steps of group verification of springboot entity-class field verification. For more related springboot group verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!