我希望我的可审计(@CreatedDate和@LastModifiedDate) MongoDB文档能够使用ZonedDateTime字段。
显然,Spring不支持这种类型(请看一下org.springframework.data.auditing.AnnotationAuditingMetadata)。
框架版本:SpringBoot2.0.0和Spring Data MongoDB 2.0.0
Spring数据审计错误:
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 MongoConfiguration {
}可审计实体:
public abstract class BaseDocument {
@CreatedDate
private ZonedDateTime createdDate;
@LastModifiedDate
private ZonedDateTime lastModifiedDate;
}我试过的东西
我还尝试为ZonedDateTime创建一个自定义转换器,但Spring数据并不考虑它。类DateConvertingAuditableBeanWrapper有一个ConversionService,它在构造函数方法中配置为JodaTimeConverters、Jsr310Converters和ThreeTenBackPortConverters。
自定义转换器:
@Component
public class LocalDateTimeToZonedDateTimeConverter implements Converter<LocalDateTime, ZonedDateTime> {
@Override
public ZonedDateTime convert(LocalDateTime source) {
return source.atZone(ZoneId.systemDefault());
}
}春季数据DateConvertingAuditableBeanWrapper:
class DefaultAuditableBeanWrapperFactory implements AuditableBeanWrapperFactory {
abstract static class DateConvertingAuditableBeanWrapper implements AuditableBeanWrapper {
private final ConversionService conversionService;
}
}可以审计ZonedDateTime字段吗?
如何注册转换器?
发布于 2018-08-03 02:05:21
创建一个DateTimeProvider以提供审核时使用的当前时间:
@Component("dateTimeProvider")
public class CustomDateTimeProvider implements DateTimeProvider {
@Override
public Optional<TemporalAccessor> getNow() {
return Optional.of(ZonedDateTime.now());
}
}然后:
DateTimeProvider注释中引用@EnableMongoAuditing组件;Date和ZonedDateTime创建Dates;Converter实例添加到MongoCustomConversions实例;MongoCustomConversions实例公开为@Bean。@Configuration
@EnableMongoAuditing(dateTimeProviderRef = "dateTimeProvider")
public class MongoConfiguration {
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new DateToZonedDateTimeConverter());
converters.add(new ZonedDateTimeToDateConverter());
return new MongoCustomConversions(converters);
}
class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
@Override
public ZonedDateTime convert(Date source) {
return source == null ? null :
ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
}
}
class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
@Override
public Date convert(ZonedDateTime source) {
return source == null ? null : Date.from(source.toInstant());
}
}
}但是,我不会为此目的使用ZonedDateTime。我会坚持OffsetDateTime
OffsetDateTime,ZonedDateTime和Instant都会在时间线上存储一个瞬间,达到纳秒级的精度.瞬间是最简单的,只是表示瞬间。OffsetDateTime增加了来自UTC/格林威治的偏移量,这允许获得本地日期时间。ZonedDateTime添加了全时区规则.ZonedDateTime或Instant用于在更简单的应用程序中对数据进行建模。此类可用于更详细地建模日期时间概念,或在与数据库或网络协议通信时使用。
https://stackoverflow.com/questions/43236431
复制相似问题