2009
Feb
17

String Date property in a spring bean – No need for CustomDateEditor

A while back I struggled to use java.util.Date as property of a spring bean, as it is not straight forward. We need to write custom property editors. Spring is a fantastic framework which simplifies our lives to a great extent. But I couldn't digest this custom property editor logic for a basic object like Date.

After doing some research I found an easy way to bypass Custom Editor for setting date property in a bean.

DateUtils object from apache commons has a static method which takes String date & array of String (for date format) as parameter & returns java.util.Date object for the date String passed.
We can very well use this to set the Date property in a bean.


...

...

public class MyService {

    private Date startDate;

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getStartDate() {
        return this.startDate;
    }
}

Bean configuration

  <bean id="myService" class="com.my.package.MyService">
     <property name="startDate">
         <bean id="sDate" class="org.apache.commons.lang.time.DateUtils" factory-method="parseDate">
             <constructor-arg value="11-02-2009 14:30"/>
             <constructor-arg>
                 <list><value>MM-dd-yyyy HH:mm</value></list>
            </constructor-arg>
         </bean>
     </property>
</bean>

The trick here is that using the "factory-method" of spring bean configuration, to invoke static method of DateUtils, which takes string & pattern array.

It is not necessary that we need to use DateUtils here. Any class which provides a static method to return java.util.Date taking String as parameter.

If we had a constructor in java.util.Date object which takes String date & date format, we could have very well used it here using construct-arg elements of the bean.

Finally, we can use the same logic for setting any property provided you have a static method in a class which returns exactly what you are trying to set taking String as input parameter.

Update :
Spring manual says we need can call static methods using factory-method (provided you have not already instantiated the property bean. In the above example it is DateUtils). If you have already instantiated the property bean, you can call a normal getter using factory-method as in this example

Tags: , , , ,

Leave a Reply

You must be logged in to post a comment.