1

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?

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
l a s
  • 3,836
  • 10
  • 42
  • 61

2 Answers2

1

@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.

mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52
0

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.

NatFar
  • 2,090
  • 1
  • 12
  • 29