Spring Date Property


 

Spring Date Property

In this tutorial you will learn about spring date property and how to set in spring configuration file.

In this tutorial you will learn about spring date property and how to set in spring configuration file.

Spring Date Property

Passing a date format in the bean property is not allowed and to do so you need to declare a dateFormat bean and reference it as factory bean from its date property that is set in bean property. The SimpleDateFormat.parse() method is called from the factory method to convert the String into the Date object.

Employee.java

package spring.date.property;

import java.util.Date;

public class Employee {

	private Date joiningDate;
	private String name;

	public Date getJoiningDate() {
		return joiningDate;
	}

	public void setJoiningDate(Date joiningDate) {
		this.joiningDate = joiningDate;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Employee.java

package spring.date.property;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		Employee emp = (Employee) context.getBean("bean1");
		System.out.println(emp.getJoiningDate());
	}
}

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id="customEditorConfigurer"
    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>

  <bean id="bean1" class="spring.date.property.Employee">
    <property name="name" value="Rakesh" />
    <property name="joiningDate" value="1/09/2010" />
  </bean>

</beans>

When you run this application it will display message as shown below:


Wed Sep 01 00:00:00 GMT+05:30 2010

Download this example code

Ads