Home  >  Spring

Inject Date into Spring Bean Property

By Arvind Rai, July 14, 2022
We inject Java Date into Spring bean property using Spring CustomDateEditor. The CustomDateEditor is a property editor for java.util.Date, supporting a custom java.text.DateFormat. It is a built-in PropertyEditor to handle Date. When we inject date to a bean in XML configuration, the value is string. With the help of CustomDateEditor, Spring converts string to date object.



Using CustomDateEditor


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 

Reference

Class CustomDateEditor

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us