news 2026/5/8 19:29:20

(17)注入自定义Date

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
(17)注入自定义Date

我们前面说过,java.util.Date在Spring中被当做简单类型,简单类型在注入的时候可以直接使用value属性或value标签来完成。但我们之前已经测试过了,对于Date类型来说,采用value属性或value标签赋值的时候,对日期字符串的格式要求非常严格,必须是这种格式的:Mon Oct 10 14:30:26 CST 2022。其他格式是不会被识别的。如以下代码:

packagecom.powernode.spring6.bean;importjava.util.Date;/** * @author 动力节点 * @version 1.0 * @className Student * @since 1.0 **/publicclassStudent{privateDatebirth;publicvoidsetBirth(Datebirth){this.birth=birth;}@OverridepublicStringtoString(){return"Student{"+"birth="+birth+'}';}}
<beanid="studentBean"class="com.powernode.spring6.bean.Student"><propertyname="birth"value="Mon Oct 10 14:30:26 CST 2002"/></bean>
@TestpublicvoidtestDate(){ApplicationContextapplicationContext=newClassPathXmlApplicationContext("spring.xml");StudentstudentBean=applicationContext.getBean("studentBean",Student.class);System.out.println(studentBean);}

如果把日期格式修改一下:

<beanid="studentBean"class="com.powernode.spring6.bean.Student"><propertyname="birth"value="2002-10-10"/></bean>

这种情况下,我们就可以使用FactoryBean来完成这个骚操作。
编写DateFactoryBean实现FactoryBean接口:

packagecom.powernode.spring6.bean;importorg.springframework.beans.factory.FactoryBean;importjava.text.SimpleDateFormat;importjava.util.Date;/** * @author 动力节点 * @version 1.0 * @className DateFactoryBean * @since 1.0 **/publicclassDateFactoryBeanimplementsFactoryBean<Date>{// 定义属性接收日期字符串privateStringdate;// 通过构造方法给日期字符串属性赋值publicDateFactoryBean(Stringdate){this.date=date;}@OverridepublicDategetObject()throwsException{SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");returnsdf.parse(this.date);}@OverridepublicClass<?>getObjectType(){returnnull;}}

编写spring配置文件:

<beanid="dateBean"class="com.powernode.spring6.bean.DateFactoryBean"><constructor-argname="date"value="1999-10-11"/></bean><beanid="studentBean"class="com.powernode.spring6.bean.Student"><propertyname="birth"ref="dateBean"/></bean>
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/3 10:30:50

(18)Bean的生命周期

什么是Bean的生命周期 Spring其实就是一个管理Bean对象的工厂。它负责对象的创建&#xff0c;对象的销毁等。 所谓的生命周期就是&#xff1a;对象从创建开始到最终销毁的整个过程。 什么时候创建Bean对象&#xff1f; 创建Bean对象的前后会调用什么方法&#xff1f; Bean对象什…

作者头像 李华
网站建设 2026/5/8 4:07:08

ArcGIS大师之路500技---026shp格式数据简介

文章目录前言一、 什么是SHP文件&#xff1f;一个“组合套装”二、 SHP文件能做什么&#xff1f;三种基本形态三、 为什么SHP文件如此经久不衰&#xff1f;四、 它的局限性&#xff1a;英雄亦有短板五、 实战小技巧&#xff1a;在ArcGIS中与SHP文件共处总结前言 你是否曾好奇&…

作者头像 李华
网站建设 2026/4/30 23:13:44

2011-2023年中国老年社会追踪调查CLASS

数据简介 中国老年社会追踪调查&#xff08;China Longitudinal Aging Social Survey&#xff0c;CLASS&#xff09;是一个全国性、连续性、系统性、长期性的社会调查项目。通过定期、系统地收集中国老年人群社会、经济背景数据&#xff0c;掌握老年人在衰老过程中面临的各种问…

作者头像 李华
网站建设 2026/4/30 23:14:10

Ansible自动化运维入门:从手工到批量部署

本文介绍Ansible基础概念、安装配置、常用模块&#xff0c;以及实战批量部署案例。前言 管理1台服务器&#xff0c;手工操作没问题。 管理10台服务器&#xff0c;写脚本能应付。 管理100台服务器&#xff0c;必须用自动化工具。 Ansible是最流行的自动化运维工具之一&#xff0…

作者头像 李华