Home  >  Spring Core

Spring Inject Date into Bean Property | CustomDateEditor

By Arvind Rai, August 20, 2013
CustomDateEditor belongs to org.springframework.beans.propertyeditors. It is a built-in PropertyEditors to handle Date. By default it will not be available we need to configure it to work. When we inject date value to any our bean, the value will be string at that time. With the help of CustomDateEditor, spring converts string format to date format. Find the example.

spring.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="person" class="com.concretepage.bean.Person">
      <property name="name" value="Ram" />
      <property name="dob" value="01-03-1980" />
    </bean>

    <bean id="dtEditor" class="org.springframework.beans.propertyeditors.CustomDateEditor">
		<constructor-arg ref="sdtformat"/>
		 <constructor-arg value="true" />
	</bean>
	
	<bean id="sdtformat" class="java.text.SimpleDateFormat" >
	  <constructor-arg value="dd-MM-yyyy" />
	</bean>
 
	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date">
					<ref local="dtEditor" />
				</entry>
			</map>
		</property>
	</bean>
	       
</beans>
 


Person.java
package com.concretepage.bean;
import java.util.Date;
public class Person {
	private String name;
	private Date dob;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getDob() {
		return dob;
	}
	public void setDob(Date dob) {
		this.dob = dob;
	}
}
 


SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.bean.Person;
public class SpringTest {
	public static void main(String[] args) {
		ApplicationContext  context = new ClassPathXmlApplicationContext("spring.xml");
		Person person = (Person)context.getBean("person");
		System.out.println(person.getDob());
	}
}   
 


Output
Sat Mar 01 00:00:00 IST 1980
 
Download Source Code
spring-inject-date-bean-property.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us