@InitBinder in spring boot not working with @RequestBody
spring, spring-boot, spring-mvc
Solution
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
Problem
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`