【发布时间】:2019-03-11 15:33:18
【问题描述】:
我能够通过对Accessing Data with MongoDB 的官方 Spring Boot 指南进行最小修改来重现我的问题,请参阅 https://github.com/thokrae/spring-data-mongo-zoneddatetime。
向 Customer 类添加 java.time.ZonedDateTime 字段后,运行指南中的示例代码失败并出现 CodecConfigurationException:
客户.java:
public String lastName;
public ZonedDateTime created;
public Customer() {
输出:
...
Caused by: org.bson.codecs.configuration.CodecConfigurationException`: Can't find a codec for class java.time.ZonedDateTime.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46) ~[bson-3.6.4.jar:na]
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63) ~[bson-3.6.4.jar:na]
at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51) ~[bson-3.6.4.jar:na]
这可以通过在 pom.xml 中将 Spring Boot 版本从 2.0.5.RELEASE 更改为 2.0.1.RELEASE 来解决:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
现在异常消失了,客户对象包括 ZonedDateTime 字段are written to MongoDB。
我向 spring-data-mongodb 项目提交了一个错误 (DATAMONGO-2106),但我会理解是否不希望更改此行为也没有高优先级。
最好的解决方法是什么?在寻找异常消息时,我发现了几种方法,例如注册custom codec、custom converter 或使用Jackson JSR 310。我宁愿不向我的项目添加自定义代码来处理 java.time 包中的类。
【问题讨论】:
-
您找到解决方案了吗?
-
@cherit:我的具体问题是通过使用 java.time.Instant 而不是 ZonedDateTime 解决的。如果没有更好的结果,我还将在下周初发布这两种解决方法(使用转换器和编解码器)的示例实现作为答案。
标签: spring mongodb spring-boot spring-data-mongodb java-time