I use the following custom editor in MANY Spring-MVC controllers according to:
A controller
binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, NumberFormat.getNumberInstance(new Locale("pt", "BR"), true)); Other controller
binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, NumberFormat.getNumberInstance(new Locale("pt", "BR"), true)); Another controller
binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, NumberFormat.getNumberInstance(new Locale("pt", "BR"), true)); Notice the same custom editor registered
Question: how can i set up a global custom editor like this one in order to avoid set up each controller ?
regards,
What are the ways to create custom Property Editors? Explanation: You can write custom property editors by implementing the java. beans. PropertyEditor interface or extending the convenient support class java.
Register Custom PropertyEditor To register, you will need to create a method with annotation – @InitBinder . On application startup, this annotation is scanned and all the detected methods should have a signature of accepting WebDataBinder as an argument.
The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.
Starting Spring 3.2, you can use @ControllerAdvice instead of using @ExceptionHandler, @InitBinder, and @ModelAttribute in each Controller. They will be applied to all @Controller beans.
import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.context.request.WebRequest; @ControllerAdvice public class GlobalBindingInitializer { @InitBinder public void registerCustomEditors(WebDataBinder binder, WebRequest request) { binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, NumberFormat.getNumberInstance(new Locale("pt", "BR"), true)); } } If you had started out with Spring Roo generated code, or limit the annotations scanned by component-scan using include-filter, then add the required filter in webmvc-config.xml
<!-- The controllers are autodetected POJOs labeled with the @Controller annotation. --> <context:component-scan base-package="com.sensei.encore.maininterface" use-default-filters="false"> <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/> <!-- ADD THE BELOW LINE --> <context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/> </context:component-scan>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With