Spring 注入日期到bean属性

在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 Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,682评论 19 139
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 9,757评论 2 7
  • Bean的定义 被称作 bean 的对象是构成应用程序的支柱也是由 Spring IoC 容器管理的。bean 是...
    jiangmo阅读 4,905评论 0 3
  • 如果有来生,我愿做你每天喝水的那个杯子,这样,就能常常被你捧在手心,感受你手的温度,能轻易的得到你的吻,能认真端详...
    独孤邱子阅读 3,184评论 1 7
  • 虚拟现实漫游指南丨如何选购你的第一款VR眼镜 人生有许多第一次,相信每个人的第一次都是既兴奋又紧张的,购买自己的第...
    vr爱好者阅读 3,237评论 0 1