Salil Wadnerkar wrote:@Valid is processed by Spring MVC for MVC controllers, not for any other classes.
This is so that it can return a bad request (400) error on these validation failures automatically.
What solution do we have then? I want to validate the object in exactly same manner as Spring does. Does spring provide any support for that?
Claude Moore wrote:In Spring Boot you could annotate with @Validated your @Service class to get all @Valid annotated params in methods to be validated.
That changes the returned response. The "object" and "field" returned in the JSON are different with @Validated. The "object" now contains "myUserService" and the "field" conatins "myUserService.nethod.name"
Ok, done some tests: please consider following code:
What makes the difference is that the first method is handled directly by Spring, which return a quite complex response with a full trace of the validation error. Using a service, when validation isn't satisfied an exception is thrown, which is in turn returned to the caller as a much simpler JSON response.
So, which approach is best ? I'd vote for putting the validation logic in a @Service, if present: this way, one could catch the exception and handle it the way he prefers.