Reputation: 22027
In following blog entry.
https://www.baeldung.com/spring-boot-bean-validation
The author mentioned about how Spring Boot works with @Valid
annotation.
@RestController
public class UserController {
@PostMapping("/users")
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
// persisting the user
return ResponseEntity.ok("User is valid");
}
// standard constructors / other methods
}
When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument.
Is it true that @Valid
works as expected on @RestController
without @Validated
?
Then what kind of stereo types required to be explicitly annotated with @Validated
?
Upvotes: 6
Views: 3887
Reputation: 3694
Following minimal rules inferred by testing a @RestController
:
@Valid
annotation is present on the method parameter itself. The parameter type, i.e. class, itself has to be annotated by some validation constraints, but a @Validated
on the class is not necessary.@Min(1)
on method parameters require the @Validated
annotation on the @RestController
class itself. This comes in handy e.g. for @PathVariable @Size(min = 1, max = 5) Long[] ids
Upvotes: 4
Reputation: 226
Yes @Valid
will work without @Validated
in @RestController
.
In Spring, we use JSR-303's @Valid annotation for method level validation. Moreover, we also use it to mark a member attribute for validation. However, this annotation doesn't support group validation. Groups help to limit the constraints applied during validation. One particular use case is UI wizards. Here, in the first step, we may have a certain sub-group of fields. In the subsequent step, there may be another group belonging to the same bean. Hence we need to apply constraints on these limited fields in each step, but @Valid doesn't support this. In this case, for group-level, we have to use Spring's @Validated, which is a variant of this JSR-303's @Valid. This is used at the method-level. And for marking member attributes, we continue to use the @Valid annotation.
You can read more about this in this link.
Upvotes: 3