@InitBinder in spring boot not working with @RequestBody
This is an old question, but I've managed to get the @InitBinder
annotation to bind my custom Validator
to a @Valid @RequestBody
parameter like this:
@InitBinder
private void bindMyCustomValidator(WebDataBinder binder) {
if ("entityList".equals(binder.getObjectName())) {
binder.addValidators(new MyCustomValidator());
}
}
If you try to filter the bound argument by setting the value of the annotation, then it won't work for a @RequestBody
argument. So here I check the object name instead. My method parameter is actually called entities
, but Spring had decided to call it entityList
. I had to debug it to discover this.
From the docs,
Default is to apply to all command/form attributes and all request parameters processed by the annotated handler class. Specifying model attribute names or request parameter names here restricts the init-binder method to those specific attributes/parameters, with different init-binder methods typically applying to different groups of attributes or parameters.
Please have a look here
You can try my solution:
@InitBinder
private void initBinder(WebDataBinder binder) {
if (CustomerQuickRegisterEntity.class.equals(binder.getTarget().getClass())) {
binder.addValidators(new YourValidator());
}
}