【问题标题】:Why cant we inject DATE Direct from Spring?为什么我们不能从 Spring 中直接注入 DATE?
【发布时间】:2014-11-13 08:55:58
【问题描述】:

我有一个用于日期的 Bean,我在 Spring 配置 xml 中以下列方式从 spring 中注入一个 Date。

<bean id="customer" class="com.my.common.Customer">
        <property name="date" value="2014-11-12" />
    </bean>

运行后出现以下错误:

Caused by: org.springframework.beans.TypeMismatchException: 
    Failed to convert property value of type [java.lang.String] to 
    required type [java.util.Date] for property 'date'; 

nested exception is java.lang.IllegalArgumentException: 
    Cannot convert value of type [java.lang.String] to
    required type [java.util.Date] for property 'date': 
    no matching editors or conversion strategy found

为什么会这样?任何人都可以解释为什么它不起作用。

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

即使Customer#datejava.util.Date,Spring 怎么知道如何解析2014-11-12 输入字符串?当然yyyy-MM-dd 是一个很常见的日期模式,但是没有标准的默认日期模式

一种解决方案是使用工厂 bean:

<bean id="dateFormatter" class="java.text.SimpleDateFormat">
    <constructor-arg value="yyyy-MM-dd" />
</bean>

<bean id="customer" class="com.veke.common.Customer">
    <property name="date">
        <bean factory-bean="dateFormatter" factory-method="parse">
            <constructor-arg value="2014-11-12" />
        </bean>
    </property>
</bean>

【讨论】:

    【解决方案2】:

    您必须在控制器类中添加自定义 InitBinder

    @InitBinder
    public void initBinder(WebDataBinder dataBinder, Locale locale,HttpServletRequest request) {
            //set your requred date format
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy");
            dateFormat.setLenient(false);
            //spring will bind every Date String to java.util.Date
            dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,true));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-28
      • 2014-11-25
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2017-05-03
      • 2021-10-27
      • 1970-01-01
      • 2015-01-26
      相关资源
      最近更新 更多