When creating a REST controller with Spring Boot it's possible to use Bean Validation to validate the methods arguments annotating the class with @Validated.
Then Bean Validation annotations can be used directly on the argument or, if the argument is a complex class with properties that must be validated (such as the request body), using @Valid.
The inconsistency I found was while handling violation on those validations.
While using the annotations from javax.validation.constraints (the validations from the Bean Validation API) the violations are handled by the @Validated handler (MethodValidationInterceptor) and throws ConstraintViolationException.
When using @Valid the violation is handled by ModelAttributeMethodProcessor and throws MethodArgumentNotValidException.
See the problem?
The @Validated, a Spring annotation that says it is a "Variant of JSR-303's Valid" and "Designed for convenient use with Spring's JSR-303 support but not JSR-303 specific" (see it here), throws ConstraintViolationException, an exception from the Bean Validation API (JSR-303).
And the opposite also is true, the @Valid (from Bean Validation API) throws MethodArgumentNotValidException (Spring exception).
I think it would be more concise if their behavior changed between them.
Does it makes sense?
When creating a REST controller with Spring Boot it's possible to use Bean Validation to validate the methods arguments annotating the class with
@Validated.Then Bean Validation annotations can be used directly on the argument or, if the argument is a complex class with properties that must be validated (such as the request body), using
@Valid.The inconsistency I found was while handling violation on those validations.
While using the annotations from
javax.validation.constraints(the validations from the Bean Validation API) the violations are handled by the@Validatedhandler (MethodValidationInterceptor) and throwsConstraintViolationException.When using
@Validthe violation is handled byModelAttributeMethodProcessorand throwsMethodArgumentNotValidException.See the problem?
The
@Validated, a Spring annotation that says it is a "Variant of JSR-303's Valid" and "Designed for convenient use with Spring's JSR-303 support but not JSR-303 specific" (see it here), throwsConstraintViolationException, an exception from the Bean Validation API (JSR-303).And the opposite also is true, the
@Valid(from Bean Validation API) throwsMethodArgumentNotValidException(Spring exception).I think it would be more concise if their behavior changed between them.
Does it makes sense?