Spring注入日期到bean屬性-CustomDateEditor

這一個Spring例子向您展示如何爲bean屬性注入一個「日期」。

package com.yiibai.common;

import java.util.Date;

public class Customer {

Date date;

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

@Override
public String toString() {
    return "Customer \[date=" + date + "\]";
}

}

bean配置文件

<bean id="customer" class="com.yiibai.common.Customer">
    <property name="date" value="2015-12-31" />
</bean>

執行-運行程序輸出

package com.yiibai.common;

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

public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");

    Customer cust = (Customer) context.getBean("customer");
    System.out.println(cust);

}

}

可能會遇到如下錯誤信息:

Caused by: org.springframework.beans.TypeMismatchException:
Failed to convert property value of type [java.lang.String] to
required type [java.util.Date] for property 'date';

nested exception is java.lang.IllegalArgumentException:
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中,可以通過兩種方式注入日期:

1. Factory bean

聲明一個dateFormat bean,在「customer」 Bean,引用 「dateFormat」 bean作爲一個工廠bean。該工廠方法將調用SimpleDateFormat.parse()自動轉換成字符串Date對象。

<bean id="dateFormat" class="java.text.SimpleDateFormat">
    <constructor-arg value="yyyy-MM-dd" />
</bean>

<bean id="customer" class="com.yiibai.common.Customer">
    <property name="date">
        <bean factory-bean="dateFormat" factory-method="parse">
            <constructor-arg value="2015-12-31" />
        </bean>
    </property>
</bean>

2. CustomDateEditor

聲明一個 CustomDateEditor 類將字符串轉換成 java.util.Date。

    <constructor-arg>
        <bean class="java.text.SimpleDateFormat">
            <constructor-arg value="yyyy-MM-dd" />
        </bean>
    </constructor-arg>
    <constructor-arg value="true" />
</bean>

並聲明另一個「CustomEditorConfigurer」,使 Spring轉換 bean 屬性,其類型爲java.util.Date。

bean配置文件的完整例子(applicationContext.xml)。

<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="customer" class="com.yiibai.common.Customer">
    <property name="date" value="2015-12-31" />
</bean>

下載代碼 – http://pan.baidu.com/s/1bxZyfO