If I use @InitBinder without limiting it,it is working fine with @RequestBody to validate my objects.
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(method=RequestMethod.POST)
public CustomerQuickRegisterEntity saveNewCustomer(@Valid @RequestBody CustomerQuickRegisterEntity customerEntity,BindingResult result)
{
if(result.hasErrors())
{
return new CustomerQuickRegisterEntity();
}
return customerQuickRegisterRepository.save(customerEntity);
}
But problem is that when i limit it to just one object by doing it as @InitBinder("customerEntity")
it is not validating the object. So I have searched through stackoverflow and found that @InitBinding
only works with objects annotated with @ModelAttribute
. Then my question is that it is working fine with @RequestBody
when I use it as @InitBinder
but does not work well when I use it as @InitBinder("customerEntity")
...why is it so?
Is there any other way to validate Objects(Not properties of object Individually) associated with @RequestBody
public class WebDataBinder extends DataBinder. Special DataBinder for data binding from web request parameters to JavaBean objects. Designed for web environments, but not dependent on the Servlet API; serves as base class for more specific DataBinder variants, such as ServletRequestDataBinder .
Annotation Type InitBinderAnnotation that identifies methods that initialize the WebDataBinder which will be used for populating command and form object arguments of annotated handler methods.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With