更多的Spring框架引入了转换和格式化服务的最新版本,以充分利用这些任务的照顾,不知何故离开属性编辑器系统之后。但是,报告的问题不幸仍然存在:默认的DateFormatter
is unable to properly convert空字符串到null
Date
对象。我发现非常恼人的是Spring文档contains a date formatter snippet example where the proper guard clauses are implemented这两个转换(来自和来自字符串)。框架实现和框架文档之间的这种差异确实使我非常疯狂,以至于我一有时间就会致力于完成任务,甚至可以尝试提交补丁。
在此期间,我建议大家在使用Spring框架的现代版遇到此问题是继承默认DateFormatter
并覆盖其parse
方法(其print
方法也一样,如果它需要的话),以增加以文档中显示的形式出现的警卫条款。
package com.example.util;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
public class DateFormatter extends org.springframework.format.datetime.DateFormatter {
@Override
public Date parse(String text, Locale locale) throws ParseException {
if (text != null && text.isEmpty()) {
return null;
}
return super.parse(text, locale);
}
}
然后,一些修改必须被施加到XML Spring配置:转换服务豆必须被定义,并且在mvc
命名空间中的annotation-driven
元件相应的属性必须正确设置。
<mvc:annotation-driven conversion-service="conversionService" />
<beans:bean
id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<beans:property name="formatters">
<beans:set>
<beans:bean class="com.example.util.DateFormatter" />
</beans:set>
</beans:property>
</beans:bean>
要提供具体的日期格式,该DateFormatter
bean的pattern
属性必须正确设置。
<beans:bean class="com.example.util.DateFormatter">
<beans:property name="pattern" value="yyyy-MM-dd" />
</beans:bean>
如果你没有注册一个自定义的PropertyEditor,它对于非空字符串如何工作? – axtavt 2011-01-26 16:15:05
由于Spring有一些内置的PropertyEditors,如下所示:http://static.springsource.org/spring/docs/3.0.3.RELEASE/spring-framework-reference/html/validation.html#beans-beans-转换 – 2011-01-27 12:47:11