Related to #11041.
I'm trying to validate @PathVariable
and @RequestBody
in one method. MethodValidationPostProcessor
is registered. Simplified Controller looks like this:
@RestController
@Validated
public class MyController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity method_name(@PathVariable @NotNull String id, @Valid @RequestBody Body body) {
/// Some code
}
}
I noticed that request body validation is triggered twice - it wouldn't be an issue if it weren't custom ConstraintValidator
with injected bean:
public class CustomValidator implements ConstraintValidator<Body, String> {
@Autowired
private BodyVerificator bodyVerificator;
...
For first validation run the bean is injected properly, and for second run it's null so it results in NPE. Workaround is to either not use method parameter validation at all, or to annotate @RequestBody
with @Validated
so not mix @Validated
and @Valid
. I would actually prefer to have @PathVariable
bean validation support in Spring like in #11041.
Comment From: encircled
Hi,
Use annotation @Validated
instead of @Valid
for @RequestBody
parameter. Then MethodValidationPostProcessor
will not be triggered and Spring arguments validation (with dependencies injection for validators) will still work.
Comment From: rstoyanchev
Team decision: we are going to provide first-class support for bean validation that's built at the web framework level (Spring MVC and WebFlux), without requiring a separate post-processor and an AOP proxy.
Comment From: rstoyanchev
I'm closing this in favor of #29825 that summarizes issues with validation across multiple issues, and also highlights some of the design questions. Please take a look and provide further feedback if necessary under the new issue.