Search code examples
javaspringspring-mvcautowiredspring-3

@Value for initializing java.util.Date in Spring 3


I have a Employee class with a java.util.Date type member variable like this:

@Component(value="employeeBean")
public class Employee {
// How to initialize this using @Value ???
private Date dateOfJoining;
}

Using the application context xml this can be done using this:

<bean id="dateFormat" class="java.text.SimpleDateFormat">
    <constructor-arg value="yyyy-MM-dd" />
</bean>

<bean id="employeeBean" class="com.Employee">
    <property name="dateOfJoining">
        <bean factory-bean="dateFormat" factory-method="parse">
            <constructor-arg value="2010-01-31" />
        </bean>
    </property>
</bean>

But I want to do this using Annotations. Please advice.


Solution

  • @Value("#{dateFormat.parse('2010-01-31')}")
    private Date dateOfJoining;
    

    You can use SpEL enclosed with #{} in @Value annotation