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.
Example
Spring Controller
@Controller
@RequestMapping("/")
public class TradeController {
@GetMapping("/trade")
@ResponseBody
public String handleRequest(@RequestParam Date tradeDate) {
return "request received for " + tradeDate;
}
}
Java Config class
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurationSupport {
@Override
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {
ConfigurableWebBindingInitializer initializer = super.getConfigurableWebBindingInitializer();
initializer.setPropertyEditorRegistrar(propertyEditorRegistry -> {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
propertyEditorRegistry.registerCustomEditor(Date.class,
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
Output
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 ProjectDependencies 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
|