当前位置: 首页 > news >正文

FactoryBean 实战练习 - 注入自定义 Date

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

采用工厂方法模式以非简单类型的方式通过 FactoryBean 接口实例化,我们可以在工厂方法中创建Date对象,同时还可以对Date对象进行加工,从而创建我们需要格式的日期对象。

/*** ClassName: DateFactoryBean* Package: cw.spring.study.bean* Description:* DateFactoryBean 这是一个工厂Bean,* 用于协助Spring创建Date对象*/
public class DateFactoryBean implements FactoryBean<Date> {private String dateStr; // 日期字符串(简单类型)public void setDateStr(String dateStr) {this.dateStr = dateStr;}@Overridepublic Date getObject() throws Exception {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");return dateFormat.parse(dateStr);}@Overridepublic Class<?> getObjectType() {return null;}
}
<!-- 利用工厂Bean DateFactoryBean 创建指定日期的Date对象 -->
<bean id="date1" class="cw.spring.study.bean.DateFactoryBean"><property name="dateStr" value="2023-05-22"/>
</bean><bean id="student" class="cw.spring.study.bean.Student"><property name="birth" ref="date1"/>
</bean>


http://www.mrgr.cn/news/17342.html

相关文章:

  • 对字符、字符串的研究
  • python3.10安装
  • Python类详解
  • python办公自动化:使用`Python-PPTX`添加图表
  • RoadLib---这两年值得一看的建图定位项目
  • MC药水酿造
  • Mac系统内存怎么清理:一篇让你轻松摆脱卡顿的指南
  • 【Unity实战】Visual Studio Debug失败
  • 【Redis】Redis 客户端开发与 Java 集成:RESP协议解析与实战操作
  • 毕业论文免费查重网站
  • MicroNet关键代码解读(Micro-block与Dynamic Shift-Max的实现代码)
  • postgis
  • Vue 全局数据:提升开发效率的利器
  • Go语言的前世今生与未来展望
  • ⾳频重采样及基本概念
  • 数据结构:(LeetCode101)对称二叉树
  • 驱动开发系列17 - PCI总线
  • World of Warcraft [CLASSIC][80][Grandel]Sapphire Hive Drone
  • C语言中的预处理指令的其中之一——#line
  • 《JavaEE进阶》----7.<SpringMVC实践项目:【登录页面的验证】>