Java 为什么我们不能直接从春天开始?

Java 为什么我们不能直接从春天开始?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我有一个用于Date的Bean,我以如下方式在spring配置xml中从spring注入一个日期 <bean id="customer" class="com.my.common.Customer"> <property name="date" value="2014-11-12" /> </bean> 为什么会这样?任何人都可以解释为什么它不起作用。即使客户#日期是java.util.date,Spring怎么知道如何解析2014-

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

<bean id="customer" class="com.my.common.Customer">
        <property name="date" value="2014-11-12" />
    </bean>
为什么会这样?任何人都可以解释为什么它不起作用。

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

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


您必须在控制器类中添加自定义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));
}
这可能会有帮助
@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));
}