简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM