views:

1109

answers:

2

Hi,

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,

+2  A: 

You need to declare it in your application context:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors"><map>
    <entry key="java.math.BigDecimal">
      <bean class="org.springframework.beans.propertyeditors.CustomNumberEditor">
      ... <!-- specify constructor-args here -->
      </bean>
    </entry>
  </map></property>
</bean>

Details are here

ChssPly76
Does it override default Spring PropertyEditors ?
Arthur Ronald F D Garcia
Yes. Page I linked to above specifically states that (Table 5.2. Built-in PropertyEditors)
ChssPly76
The customEditors property is deprecated, and will be removed in Spring 3 (according to the javadoc). You should use the PropertyEditorRegistrars property instead.
skaffman
@skaffman - you're right, thanks. It's not actually marked as deprecated (it only says so in the comment), so I've never noticed that. `propertyEditorRegistrars` is the way to go.
ChssPly76
A: 

Hi,

If you use a annotation based controller (Spring 2.5+), you can use a WebBindingInitializer to register global property editors. Something like

public class GlobalBindingInitializer implements WebBindingInitializer {

    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy", true);
    }

}

So in your web application context file, declare

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean class="GlobalBindingInitializer"/>
    </property>
</bean>

This way all annotation based controller can use any property editor declared in GlobalBindingInitializer.

regards,

Arthur Ronald F D Garcia