Reputation: 3923
Spring MVC's @Valid
annotation works as expected with @RequestBody
arg but it's not working with RequestEntity
arg. Is there anyway to get it working?
Upvotes: 1
Views: 2316
Reputation: 2220
The @Valid
annotation worked with @RequestBody
because the RequestResponseBodyMethodProcessor
(which does the work of resolving this handler argument) looks for the presence of @Valid
and, if it is found, applies all matching validators it finds in the WebDataBinder
.
On the other hand, ResponseEntity
arguments are resolved by HttpEntityMethodProcessor
, which does not perform validation even if the argument is annotated with @Valid
.
You can, of course, perform validation manually in the handler method by invoking a validator of your choosing. It’s certainly possible, although you might want to consider a different approach.
Upvotes: 0
Reputation: 4451
@Valid
is not from Spring MVC, @Valid
relies under package javax.validation;
Maybe you meant @Validated
. Nevertheless @RequestBody
and RequestEntity
have to be taken differently in terms of validation.
@RequestBody
is used in a Spring MVC Controller to annotate the payload of a request, but has nothing to do with validation of this incoming payload object.
RequestEntity
is used to wrap the actual payload in preparation for a new request. No validation is applied when you create a new RequestEntity.
Upvotes: 1