Description
Affects: spring-web-6.1.6
Hi,
I encountered some unexpected behavior with the new built-in handler method validation.
In my example my handler method has two parameters, one path variable and one request body:
@PostMapping("/{pathVariable}/test1")
String test1(@PathVariable("pathVariable") String pathVariable, @RequestBody DemoTransport demoTransport) {
return "SUCCESS";
}
The issue occurs when I want to validate the DemoTransport
by adding an @Valid
annotation. The validation is performed differently depending on whether another constraint annotation is present on any of the paramaters, for example on pathVariable
.
I prepared a small demo, here are my two controller methods. Both have the @Valid
transportation and one has an additional @NotNull
annotation on the pathVariable
.
Here are the tests with my expectations. If my requests correctly supplies a non-null pathVariable but an invalid DemoTransport
I expect the same HandlerMethodValidationException
to be thrown for both controller methods. For the handler method with the @NotNull
annotation the handler method is validated and the HandlerMethodValidationException
is correctly thrown, because this condition evaluates to true. For the handler method without the @NotNull
annotation no hander method validation is performed, only a org.springframework.web.bind.MethodArgumentNotValidException
is thrown, because this check does not evaluate to true because DemoTransport
is not isIndexOrKeyBasedContainer
.
I don't think the presence of an annotation on another parameter should influence whether the validation of the parameter annoted with @Valid
is performed as part of the method handler validation or not. I am not sure I understand why, in this case, only an index- or key-based container can be validated? Apparently the parameter is correctly validated as seen by the other controller method.
Is it possible to remove this check and always validate the method when an @Valid
is present on one of the parameters?
Consistent behavior is important for us for multiple reasons, for example because we are using ControllerAdvice and want to rely on the HandlerMethodValidationException
to be thrown.
Thank you, and please let me know if I can help.