Date简单类型的setter注入

在Spring框架中,你可以使用XML配置文件或者注解的方式为bean的属性注入值。对于Date类型的属性,比如你提到的setBirth(Date birth)方法,你可以使用Spring的标签结合注入一个日期值

  • 实体类
public class SimpleValueType{
    private Date birth;

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    // 省略其他方法和getter
}
  • 常见的做法是在代码中处理日期的转换,而不是在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);
    }

    // 省略其他方法和getter
}
  • spring配置文件
<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 对象本身并不包含格式信息。

posted @ 2024-05-23 23:57  文采杰出  阅读(3)  评论(0编辑  收藏  举报