在Spring Boot项目中,我使用@CreatedDate之类的注释来保存有关创建/更新相应文档的日期的信息 . ZonedDateTime在整个项目中使用,因此带注释的字段也是ZonedDateTime . 要启用Mongo的日期格式和ZonedDateTime之间的转换,请使用自定义转换器 .

现在,在使用Spring Boot 1.5.x时,自定义转换器可以完美地用于可审计字段 . 在Spring Boot 2.0.x中,自定义转换器适用于所有字段,但不适用于可审计的字段 . 因此,如果我删除@EnableMongoAuditing,一切正常(整个项目中的所有ZonedDateTime字段都被持久化并正确地从Mongo读取),但创建/更新的日期字段为空 . 如果我启用mongo审计,则在尝试保存文档时会出现以下异常:

java.lang.IllegalArgumentException: Invalid date type for member <MEMBER NAME>!
Supported types are [org.joda.time.DateTime, org.joda.time.LocalDateTime, java.util.Date, java.lang.Long, long]

我的Mongo配置:

@Configuration
@EnableMongoAuditing
public class MongoConfig {
    @Bean
    public MongoCustomConversions customConversions(){
        List<Converter<?,?>> converters = new ArrayList<>();
        converters.add(new ZonedDateTimeToDateConverter());
        converters.add(new DateToZonedDateTimeConverter());
        return new MongoCustomConversions(converters);
    }
}

这是相应字段的外观:

abstract class BaseModel {

    @Id
    private String id;
    @CreatedDate
    private ZonedDateTime created;
    @LastModifiedDate
    private ZonedDateTime updated;
}

有没有办法让转换器适用于mongo可审计字段,而不是降级到Spring Boot 1.5.x?