spring-boot - MongoDbConverters 用于多态类型的混合集合
问题描述
我有一个 mongo 集合,其中包含所有相同基本类型的元素。有的有_class
属性,有的没有。我已经为基本元素注册了一个 mongo 转换器,并且看到它在缺少 _class 属性时会被适当地触发。对于确实存在的元素,Spring 尝试为该子类型元素查找转换器,但随后失败。我已经尝试为子类型对象创建一个转换器,但我希望它只利用可能发生的“默认”行为。
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "type",
visible = true
)
abstract class ElementBase {}
class myElement: ElementBase{}
我的转换器适用于没有_class
属性的元素
class ElementConverter : Converter<Document, ElementBase> {
override fun convert(source: Document): ElementBase? {
// maps to object that inherits from element base
val mapper: ObjectMapper = SerializationUtils.buildJacksonObjectMapper()
return mapper.convertValue(source, myElement::class.java)
}
}
子类型对象的转换器:
abstract class SurveyElementConverterBase(val applicationContext: ApplicationContext) {
inline fun <reified T: SurveyElement> defaultConvert(source: Document): T {
// One approach, but requires that I add the type attribute to the
// document even if I'm explicitly trying to create a sub type.
// Also has problems if there are nested elements, as those elements
// also require the type attribute.
val mapper: ObjectMapper = SerializationUtils.buildJacksonObjectMapper()
return mapper.convertValue(source, T::class.java)
// Results in a stack overflow
val mongoTemplate: MongoTemplate = applicationContext.getBean(MongoTemplate::class.java)
return mongoTemplate.converter.read(T::class.java, source)
}
}
当存在 _class 属性时,我可以使用默认的转换器行为吗?或者我如何设置转换器,以便它在知道子类型时认为不需要使用自定义转换器?
Spring Boot 2.4 Kotlin 1.4.32 Spring Data Mongo 3.1
解决方案
推荐阅读
- vb.net - 如何使该程序作为 OOP 程序工作,以便我可以在代码中的任何地方使用我的数组?
- android - 应用未显示在 Google Play 商店搜索结果中
- javascript - 如何划分 XML 元素列表并根据节点的日期用 javscript 解析它?
- amazon-web-services - 使用 Route 53 在我的 EC2 实例 (AWS) 中连接多个 SMTP 服务器(Gsuite 和 Namecheap 私人邮件服务器)
- css - 输入的CSS大小::与输入相同的大小
- python - 读取包含错误编码的某些行的 csv 文件并向用户返回不正确的行
- javascript - 有没有更好的方法来编写这样的函数
- python - python,闭环和松弛客户端
- jquery - 如何获取链接以使用 JavaScript 生成的 Z-index
- java - 无法让 android webview 在 android 9 上打开文件选择器