Saturday, October 13, 2007

Spring and PropertyEditors, important details

As mentioned in the documentation, the Spring Framework uses property editors in two places:
1) When parsing ApplicationContexts from XML configuration files
2) When binding beans from HTTP requests.

It's all well and good if the only classes you need to bind are already covered by the editors built in with the Spring Framework, but if you need property editors for other kinds of classes, here's how to get Spring to include them, for both situations :
1) Use a CustomEditorConfigurer like so :

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.text.DateFormat">
<bean class="com.mypackage.CustomDateFormatEditor"/>
</entry>
<entry key="java.util.TimeZone">
<bean class="com.mypackage.TimeZoneEditor"/>
</entry>
<entry key="java.text.MessageFormat">
<bean class="com.mypackage.CustomMessageFormatEditor"/>
</entry>
<entry key="java.text.NumberFormat">
<bean class="com.mypackage.CustomNumberFormatEditor"/>
</entry>
</map>
</property>
</bean>

* Note * : The editors can be singletons because they're going to be the only instances needed by the application context to parse string values.

2) Implement and instantiate (or otherwise use) an implementation of PropertyEditorRegistrar. This will be used with your form controllers to register property editors for individual fields or whole types.

No comments: