javaspringspring-mvcpropertyeditorspring-mvc-initbinders

Spring @initBinder method to be called only once inside a controller


I have a class that annotated with @RestController and @ControllerAdvice that has my requests mapped methods (@RequestMapping). Also in this class I added a method public void initBinder(WebDataBinder dataBinder) that is annotated with @InitBinder and responsible to register some custom editor. Specifically, it is a propertyEditor that convert String to Enum.

I noticed that on every call to @RequestMapping method in my controller, my initBinder method is being called. Since in my opinion this editor registration should happen only once (initialization of controller), I want this to be set (called) only once.

Is there a way to do so?


Solution

  • Alternatively, you can use implementation of BindingInitializer for registering your custom Editor. You have to define a bean of class "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" in your app context file and set its "webBindingInitializer" property with your implementation of BindingInitializer.

    In any case, scope of WebDataBinder is for a request. Hope this helps.