美文网首页
Spring 注入日期到bean属性

Spring 注入日期到bean属性

作者: ChanHsu | 来源:发表于2017-04-28 15:58 被阅读52次

在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.springapp.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。

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

相关文章

网友评论

      本文标题:Spring 注入日期到bean属性

      本文链接:https://www.haomeiwen.com/subject/xeqazttx.html