如何在spring mvc中注册LocalDate的全局数据绑定?

我想在使用spring-mvc创建的Servlet使用LocalDate作为类型。 用户应该能够以多种有效格式提供日期yyyyMMdd, yyyy-MM-dd, yyMMdd, yy-MM-dd

因此,我正在尝试为该类注册我自己的转换器,并在整个应用程序中全局注册它 。 但它永远不会被接受

问题:我的自定义编辑器从未被调用过。

 @Bean public CustomEditorConfigurer init() { CustomEditorConfigurer c = new CustomEditorConfigurer(); c.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] { (registry) -> registry.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor()) }); return c; } public class LocalDatePropertyEditor extends PropertyEditorSupport { @Override public void setAsText(String text) { this.setValue(LocalDate.parse(text, DateTimeFormatter.ISO_DATE)); } @Override public String getAsText() { return this.getValue().toString(); } } @RestController public void DateServlet { @RequestMapping("/test") public void test(@RequestParam LocalDate date) { } } 

致电时: localhost:8080/test?date=2017-07-05

例外: Parse attempt failed for value [2017-07-05]

在调试期间,我可以看到从未调用过LocalDatePropertyEditor类。 但为什么?

我仍然不知道为什么PropertyEditor不起作用。 但以下解决方案有效。

 @Configuration public class LocalDateConfig extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { super.addFormatters(registry); registry.addFormatterForFieldType(LocalDate.class, new Formatter() { //override parse() and print() }); } }