![80aceeb45049065556362f59a479b42d.png](https://img-blog.csdnimg.cn/img_convert/80aceeb45049065556362f59a479b42d.png)
背景
项目中使用LocalDateTime系列作为dto中时间的类型,但是spring收到参数后总报错,为了全局配置时间类型转换,尝试了如下3中方法。
注:本文基于Springboot2.0测试,如果无法生效可能是spring版本较低导致的。PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam、PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数使用ModelAttributeMethodProcessor进行处理,而这个处理器要通过反射实例化一个对象出来,然后再对对象中的各个参数进行convert,但是LocalDate类没有构造函数,无法反射实例化因此会报错!!!
当LocalDateTime作为RequestParam或者PathVariable时
这种情况要和时间作为Json字符串时区别对待,因为前端json转后端pojo底层使用的是Json序列化Jackson工具(HttpMessgeConverter);而时间字符串作为普通请求参数传入时,转换用的是Converter,两者有区别哦。
在这种情况下,有如下几种方案:
1. 使用Converter
![a60559cec7ea102eed6a2ef2dafe94e5.png](https://img-blog.csdnimg.cn/img_convert/a60559cec7ea102eed6a2ef2dafe94e5.png)
以上两个bean会注入到spring mvc的参数解析器(好像叫做ParameterConvers