在Spring框架中,你可以使用XML配置文件或者注解的方式为bean的属性注入值。对于Date类型的属性,比如你提到的setBirth(Date birth)方法,你可以使用Spring的标签结合注入一个日期值
| public class SimpleValueType{ |
| private Date birth; |
| |
| public void setBirth(Date birth) { |
| this.birth = birth; |
| } |
| |
| |
| } |
- 常见的做法是在代码中处理日期的转换,而不是在Spring配置文件中。你可以在Person类中添加一个接受字符串类型参数的setBirth方法,并在该方法内部将字符串转换为Date对象。然后,你可以在Spring配置文件中直接注入一个字符串形式的日期。
将上述实体类修改
| public class SimpleValueType{ |
| private Date birth; |
| |
| public void setBirth(String birthStr) throws ParseException { |
| SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); |
| this.birth = sdf.parse(birthStr); |
| } |
| |
| |
| } |
| <bean id="svt" class="com.example.Person"> |
| <property name="birth" value="2023-03-15"/> |
| </bean> |
| @Test |
| public void testSimpleClassTest(){ |
| ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml"); |
| SimpleValueType svt = classPathXmlApplicationContext.getBean("svt", SimpleValueType.class); |
| System.out.println(svt); |
| } |
输出birth=Thu Jan 02 00:00:00 CST 2020
返回的是一个 Date 对象,而 Date 对象本身并不包含格式信息。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)