How to inject date into spring bean with CustomDateEditor?
In this example shows how to inject Date property in the spring bean using CustomDateEditor. The CustomDateEditor is a
Spring API class, supporting the custom java.text.DateFormat. In order to use CustomDateEditor for date injection in the given spring
bean property, we must have to define the CustomDateEditor and register it to spring using CustomEditorConfigurer.
package com.java2novice.beans;
import java.util.Date;
public class Employee {
private int empId;
private String name;
private String role;
private Date doj;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Date getDoj() {
return doj;
}
public void setDoj(Date doj) {
this.doj = doj;
}
public void testMe(){
System.out.println("Employee: Doj: "+this.doj);
}
}
|
XML based configuration file:
<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-3.0.xsd">
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
<bean id="myEmployee" class="com.java2novice.beans.Employee">
<property name="doj" value="23-03-1982" />
</bean>
</beans>
|
Here is the spring bean demo class:
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.Employee;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
Employee myEmp = (Employee) context.getBean("myEmployee");
myEmp.testMe();
}
}
|
|