PropertyEditors in Spring 3

PropertyEditor is an interface that provides a support for the conversion of the value of a property (usually of type String) in an object that can be Date, URL, etc.
In the Spring beans are defined in a configuration file and the values of their properties are always written as strings such as:

where the property “number” contains the value “10” as string and not as a number, even if in the java class of the bean the member “number” is defined as int as shown by the following example:

  1. create the file pom.xml

    alternatively, if you do not use Maven, you can import the following .jar files in the folder “lib”:

    • spring-context-3.1.2.RELEASE.jar
    • spring-aop-3.1.2.RELEASE.jar
    • aopalliance-1.0.jar
    • spring-beans-3.1.2.RELEASE.jar
    • spring-core-3.1.2.RELEASE.jar
    • commons-logging-1.1.1.jar
    • spring-expression-3.1.2.RELEASE.jar
    • spring-asm-3.1.2.RELEASE.jar
    • log4j-1.2.17.jar
  2. create the file conf/app-context.xml (the folder “conf” must be in the classpath)
  3. create the file conf/log4j.xml (the folder “conf” must be in the classpath)
  4. create the file eu/lucazanini/propertyeditors/Main.java
  5. create the file eu/lucazanini/propertyeditors/SimpleBean.java

The output is:

Note that the string “10” has been converted into the corresponding integer and the string “http://www.lucazanini.eu” has been used to create an object of class URL.
This happens because Spring registers and implicitly uses some PropertyEditors and among them there are CustomNumberEditor and URLEditor.
There are other PropertyEditors you must register explicitly as CustomDateEditor that requires you specify the date format.
To check this, add the following property to simpleBean in app-context.xml:

If you run the application you get the following error:

In order to register a CustomDateEditor and thus avoid this error, replace the file app-context.xml

Now the output is:

References:
Validation, Data Binding, and Type Conversion
Package org.springframework.beans.propertyeditors

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.