Spring found them another use: it’s typically what needs to be done when parsing a Spring beans definition file in order to create beans in the factory. Have you Spring users noticed you can set a number to a property and it is taken as such?
It’s because in every bean factory, there’re some editors registered by default. In fact, there are three kinds of editors:
- The first level consist of those default editors.
- If you need to go further, you can register editors provided by the Spring framework.
- Finally, you can also create your own editors.
The list of editors built-in, pre-registeredor not, is available in the Spring documentation.
For example, the
LocaleEditor is built-in and to use it, we only have to provide the correct locale string representation like so:
<bean id="dummy" class="ch.frankel.blog.spring.propertyeditor.Dummy"> <property name="locale" value="fr_FR" /> </bean>
Interestingly enough, some other editors are not well-known, like the
PatternEditor, although they are registered by default.
In order to register other property editors, whether built-in or homemade, just configure the
customEditors map property of the
org.springframework.beans.factory.config.CustomEditorConfigurer bean. Note that the latter can safely remain anonymous.
The following configuration snippet adds a date property editor so that dates can easily be configured in beans definitions files.
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date"> <bean class="org.springframework.beans.propertyeditors.CustomDateEditor"> <constructor-arg index="0"> <bean class="java.text.SimpleDateFormat"> <constructor-arg value="dd.MM.yyyy" /> </bean> </constructor-arg> <constructor-arg index="1" value="false" /> </bean> </entry> </map> </property> </bean>
Note that keys in the custom editors map are the wanted object type, meaning there can be only a single editor for each type – a good thing if there’s one.
Sources for this article can be found here in Eclipse/Maven format.