spring-mvcspring-mvc-initbinders

Can a method annotated with @InitBinder be marked as static?


Looking at the docs and several examples of @InitBinder online, I never see these methods marked as static. My IDE is claiming they can be marked as static, I don't see any errors while doing so, and conceptually I would think you can mark it this way.

Are there any downsides to doing so? I understand that the method must not return a value.


Solution

  • The code inside Spring Web that handles @InitBinder annotation does not make any assumptions or requirements whether it is static or not.

    The difference between static and non-static @InitBinder method boils down to standard Java semantics of static and non-static methods, meaning the access to non-static variables and an ability to override the method.

    If you do not need the instance variables or methods, you can safely make @InitBinder method static, and also private.

    Regardless of whether the @InitBinder method static or not, it can be called multiple times per request, like at least once for each @PathVariable, @RequestParam, @RequestHeader or @CookieValue parameter of the request processing method. You can check the target bound to the WebDataBinder object using WebDataBinder#getObjectName() and customize the binder configuration based on that information.