/ PROPERTY, SPRING

Property editors

In Java, property editors are seldom used. Originally, they were meant for Swing applications to transform between model objects and their string representations on the GUI.

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:

  1. The first level consist of those default editors.
  2. If you need to go further, you can register editors provided by the Spring framework.
  3. 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.

Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Property editors
Share this