While I was debugging my Spring Boot application I noticed that methods annotated with @InitBinder are invoked for every incoming request.
@InitBinder("categories")
public void bindFields(WebDataBinder binder) {
binder.registerCustomEditor(Set.class, new CustomPropertyEditor());
}
In @InitBinder methods we are setting a PropertyEditor to a binder. I can't understand why should these methods be called again and again and set the same thing?
Does Spring create a new WebDataBinder object for every single request?
@InitBinderplays the role to identify the methods which used to initializeWebDataBinder. Initbinder is usually used to bind requestParams to custom objects.Suppose your REST controller is annotated with
@InitBinder, every request is handled within that controller will instantiate Initbinder andWebDatabinderwill bind the request params to JavaBean objects.It provides methods to assign our validator classes. Using
addValidators()andsetValidator()methods, we can assign our validators instances.Use Case: Suppose Sun, Jan 20 is in the request param and you want to have a
LocalDateObject parsed everytime from request parm. You can add that parser logic withinWebDatabinderand have that date validated/parsed everytime the request is made.Reference: What is the purpose of init binder in spring MVC