问题描述
如何将自定义转换器添加到mu spring boot应用程序? 我的实体字段
@CreatedDate
@Column(value = "create_time")
private Instant createTime;
我的转换器是
@Bean
public Converter<Long,Instant> longInstantConverter() {
return new Converter<Long,Instant>() {
@Override
public Instant convert(Long source) {
return Instant.ofEpochMilli(source);
}
};
}
@Bean
public Converter<Instant,Long> instantLongConverter() {
return new Converter<Instant,Long>() {
@Override
public Long convert(@NotNull Instant source) {
return source.toEpochMilli();
}
};
}
org.springframework.data.mapping.MappingException: Could not read property @org.springframework.data.relational.core.mapping.Column(value=create_time) @org.springframework.data.annotation.CreatedDate()private java.time.Instant com.example.database.model.MyTable.createTime from result set!
.........
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Long] to type [java.time.Instant]
........
我该如何解决,请帮助我!
解决方法
您需要向 R2DBC 注册转换器:
@Bean
public R2dbcCustomConversions customConversions() {
List<Converter<?,?>> converters = new ArrayList<>();
converters.add(new SomeReadConverter());
converters.add(new SomeWriteConverter());
return new R2dbcCustomConversions(converters);
}
您不需要覆盖整个 R2dbcConfiguration。
,尝试分别创建ReadingConverter
和WritingConverter
,并将它们注册在Config文件中。
public class DatabaseConfig extends AbstractR2dbcConfiguration {
//...
@Override
protected List<Object> getCustomConverters() {
return List.of(
new PostReadingConverter(),new PostStatusWritingConverter()
);
}
}
检查完整的代码here。
对于Spring Boot应用程序,请尝试override the default beans。