小编tdk*_*cke的帖子

使用Spring Boot> = 2.0.1将ZonedDateTime保存到MongoDB时发生CodecConfigurationException

通过对用于通过MongoDB访问数据的官方Spring Boot指南进行了最小的修改,我能够重现我的问题,请参阅https://github.com/thokrae/spring-data-mongo-zoneddatetime

在将java.time.ZonedDateTime字段添加到Customer类之后,从指南中运行示例代码失败,并出现CodecConfigurationException:

Customer.java:

    public String lastName;
    public ZonedDateTime created;

    public Customer() {
Run Code Online (Sandbox Code Playgroud)

输出:

...
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]
Run Code Online (Sandbox Code Playgroud)

这可以通过将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>
Run Code Online (Sandbox Code Playgroud)

现在,异常消失了,并将包括ZonedDateTime字段的Customer对象写入MongoDB

我在spring-data-mongodb项目中提交了一个错误(DATAMONGO-2106),但可以理解是否不希望更改此行为,也不具有较高的优先级。

最好的解决方法是什么?当duckduckgoing为异常消息时,我找到了几种方法,如注册定制编解码器定制转换器或使用Jackson JSR 310。我宁愿不向项目添加自定义代码来处理java.time包中的类。

spring mongodb spring-data-mongodb spring-boot java.time

6
推荐指数
1
解决办法
1399
查看次数