这一个Spring例子向您展示如何为bean属性注入一个“日期”。
File:Customer.java
public class Customer {
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Customer [date=" + date + "]";
}
}
bean配置文件
<?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="customer" class="com.ray.common.Customer">
<property name="date" value="2018-02-22"/>
</bean>
</beans>
执行-运行..
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans.xml" });
Customer cust = (Customer) context.getBean("customer");
System.out.println(cust);
}
}
可能会遇到如下错误信息:
java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Date' for property 'date': no matching editors or conversion strategy found
解决办法
在Spring中,可以通过以下方式注入日期:
Factory bean
声明一个dateFormat bean,在“customer” Bean,引用 “dateFormat” bean作为一个工厂bean。该工厂方法将调用SimpleDateFormat.parse()自动转换成字符串Date对象。
<?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="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd"/>
</bean>
<bean id="customer" class="com.ray.common.Customer3">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2018-02-22"/>
</bean>
</property>
</bean>
</beans>