Spring MVC - Customizing ConfigurableWebBindingInitializer

[Updated: Dec 28, 2017, Created: Dec 27, 2017]

Spring MVC uses a WebBindingInitializer to initialize a WebDataBinder for a given request. We can use ConfigurableWebBindingInitializer to initialize a custom WebBindingInitializer.

In following example, we will register a custom PropertyEditor globally via ConfigurableWebBindingInitializer. To accomplish that, we will not use @EnableWebMvc annotation, instead we will use a plain @Configuration class which will extend WebMvcConfigurationSupport directly, we will then override getConfigurableWebBindingInitializer() method.

From @EnableWebMvc docs:

If WebMvcConfigurer does not expose some more advanced setting that needs to be configured consider removing the @EnableWebMvc annotation and extending directly from WebMvcConfigurationSupport or DelegatingWebMvcConfiguration

Note that ConfigurableWebBindingInitializer is used by RequestMappingHandlerAdapter to apply data conversion, formatting and validation for the requests.


Spring Controller

public class TradeController {

  public String handleRequest(@RequestParam Date tradeDate) {
      return "request received for " + tradeDate;

Java Config class

public class MyWebConfig extends WebMvcConfigurationSupport {

  protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {
      ConfigurableWebBindingInitializer initializer = super.getConfigurableWebBindingInitializer();
      initializer.setPropertyEditorRegistrar(propertyEditorRegistry -> {
          SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
                  new CustomDateEditor(dateFormatter, true));
      return initializer;

In above example, we are not completely replacing ConfigurableWebBindingInitializer, but rather customizing it to use a custom PropertyEditor globally.

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war


Note that, starting Spring 3.1+, a custom property editor registered via the method described here doesn't work in Spring MVC data binding.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Customizing ConfigurableWebBindingInitializer Example Select All Download
  • custom-web-binding-initializer
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also