Use Spring @Value annotation for injecting Date properties

By default, Spring does not convert a Date string defined in a property file when using the @Value annotation automatically. For example, if you have the following properties file:

aDateStr=24-10-2010

and codes

@Component
public class ValueExample
{
    @Value(“${aDateStr}”)
    Date myDate;

Spring will generate the following exceptions:

Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date]: no matching editors or conversion strategy found
 at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:58)
 at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:43)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:722)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
 ... 15 more
 Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date]: no matching editors or conversion strategy found
 at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:236)
 at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:94)
 at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:49)

One possible work around is to use Spring Expression Language (SpEL) as follows

    @Value(“#{new java.text.SimpleDateFormat(‘${aDateFormat}’).parse(‘${aDateStr}’)}”)
    Date myDate;

Note you can also define the date format desired as a property to be injected into @Value annotation. So the new property file will have the following properties defined:

aDateStr=24-10-2010

aDateFormat=dd-MM-yyyy

About these ads

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.