共计 1788 个字符,预计需要花费 5 分钟才能阅读完成。
问题形容
Spring Cloud 通过 Feign 客户端调用 HTTP 接口,如果返回值中蕴含 LocalDateTime
类型(包含其余 JSR-310 中 java.time
包的工夫类),在客户端可能会呈现反序列化失败的谬误。错误信息如下:
feign.codec.DecodeException: Type definition error: [simple type, class java.time.LocalDateTime]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-11-27T11:04:32')
Caused by: org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.time.LocalDateTime]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-11-27T11:04:32')
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-11-27T11:04:32')
问题剖析
搜寻到一个相似问题:http://blog.didispace.com/Spring-Boot-And-Feign-Use-localdate/,然而文中提供的办法并不能解决问题。
经试验,Spring Cloud 的 HTTP 接口间接调用的参数或返回值中的 LocalDateTime
类型是能够失常序列化和反序列化的,然而通过 Feign 客户端调用,反序列化时就可能产生谬误。
跟踪代码发现 Feign 客户端反序列化通过 feign.codec.Decoder
接口的实现类 SpringDecoder
最终调用org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
,这是默认的 Spring MVC 应用的HttpMessageConverter
,所以雷同的转换器在不同的调用形式下产生了不一样的后果依然不得而知。
问题解决
减少依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.9</version>
</dependency>
字段减少注解
POJO 类的 LocalDateTime
类型字段减少如下注解
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime createTime;
正文完