根据Spring documentation of DataBinder#registerCustomEditor,每个属性路径只支持一个注册的自定义编辑器。
这意味着(您可能已经知道),您将无法将两个自定义编辑器绑定到同一个类。简而言之,您不能拥有:
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/mm/yyyy"), true));
但是,您可以注册自己的 DateFormat 实现,它会按照您的意愿运行,这取决于您需要的两个 SimpleDateFormats。
例如,考虑这个自定义的DateFormat(如下),它可以解析 Dates 是"dd-MM-yyyy" 或"mm/dd/yyyy" 格式:
public class MyDateFormat extends DateFormat {
private static final List<? extends DateFormat> DATE_FORMATS = Arrays.asList(
new SimpleDateFormat("dd-MM-yyyy"),
new SimpleDateFormat("mm/dd/yyyy"));
@Override
public StringBuffer format(final Date date, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
throw new UnsupportedOperationException("This custom date formatter can only be used to *parse* Dates.");
}
@Override
public Date parse(final String source, final ParsePosition pos) {
Date res = null;
for (final DateFormat dateFormat : DATE_FORMATS) {
if ((res = dateFormat.parse(source, pos)) != null) {
return res;
}
}
return null;
}
}
然后,您只需将Date.class 绑定到基于MyDateFormat 实例构造的CustomDateEditor,如下所示:
binder.registerCustomEditor(Date.class, new CustomDateEditor(new MyDateFormat(), true));