Performance: Validation groups
Validation groups affect server-side request processing speed and response time by controlling which validations run.
Jump into concepts and practice - no test required
@Validated(Create.class) User user // only create validations run public ResponseEntity<?> createUser(@Validated(Create.class) @RequestBody User user) { ... }
@Valid User user // all validations run regardless of operation
public ResponseEntity<?> saveUser(@Valid @RequestBody User user) { ... }| Pattern | Validation Checks | CPU Usage | Response Time | Verdict |
|---|---|---|---|---|
| All validations every request | All validations run | High | Slower | [X] Bad |
| Validation groups per operation | Only relevant validations run | Lower | Faster | [OK] Good |
validation groups in Spring Boot?@NotNull(groups = CreateGroup.class) private String name; @NotNull(groups = UpdateGroup.class) private String id;
@Validated(CreateGroup.class)?CreateGroup.class, only constraints assigned to that group run.CreateGroupname field has @NotNull(groups = CreateGroup.class), so it is validated. The id field belongs to UpdateGroup, so it is skipped.name field is validated for not null -> Option B@NotNull(groups = Default.class) private String email; @NotBlank(groups = AdminGroup.class) private String role;
email when validating with @Validated(AdminGroup.class)?email field uses the Default group, while role uses AdminGroup.AdminGroup.class, only constraints in that group run. email is skipped because it belongs to Default.email is in the Default group, not AdminGroup -> Option ACreateGroup and UpdateGroup. How do you apply validation groups to a Spring Boot controller method to validate only the create rules?@Validated(GroupName.class) on the method parameter.CreateGroup.class. Using @Valid or @Validated without parameters runs default group only.@Validated(CreateGroup.class) on the method parameter -> Option A