Validation groups allow you to define sets of validation rules that apply only in certain situations, such as when creating or updating an object. This helps reuse the same model with different validation needs.
public class User { @NotNull(groups = Create.class) private String username; @NotNull(groups = Update.class) private Long id; } @PostMapping("/user/update") public ResponseEntity<?> updateUser(@Validated(Update.class) @RequestBody User user) { // method body }
The @Validated annotation with a group class tells Spring to validate only constraints that belong to that group. Constraints without a group or with other groups are ignored.
Validation groups are marker interfaces used to categorize constraints. They should be interfaces without methods or implementations.
If constraints are not annotated with the group specified in @Validated, they will not be validated. The group on constraints and the group passed to @Validated must match.
The updateProduct method validates only the Update group. The 'name' field has @NotNull for both Create and Update groups, so it is validated. The 'quantity' field has @Min only for Create group, so it is not validated here.