Spring boot 混合多态类型集合的MongodBConverter
我有一个mongo集合,其中包含的元素都是相同的基类型。其中有些具有Spring boot 混合多态类型集合的MongodBConverter,spring-boot,spring-data,spring-data-mongodb,Spring Boot,Spring Data,Spring Data Mongodb,我有一个mongo集合,其中包含的元素都是相同的基类型。其中有些具有\u class属性,有些则没有。我已经为基本元素注册了一个mongo转换器,并且看到它在缺少_class属性时被适当地激发。对于确实存在的元素,Spring尝试为该子类型元素查找转换器,但随后失败。我尝试过为子类型对象创建一个转换器,但我希望它只利用可能发生的“默认”行为 @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.E
\u class
属性,有些则没有。我已经为基本元素注册了一个mongo转换器,并且看到它在缺少_class属性时被适当地激发。对于确实存在的元素,Spring尝试为该子类型元素查找转换器,但随后失败。我尝试过为子类型对象创建一个转换器,但我希望它只利用可能发生的“默认”行为
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "type",
visible = true
)
abstract class ElementBase {}
class myElement: ElementBase{}
我的转换器,用于不带\u 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)
}
}
类元素转换器:转换器{
覆盖乐趣转换(来源:文档):ElementBase{
//映射到从元素库继承的对象
val mapper:ObjectMapper=SerializationUtils.buildJacksonObjectMapper()
返回mapper.convertValue(源代码,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)
}
}
abstract class SurveyElementConverterBase(val-applicationContext:applicationContext){
inline-fun-defaultConvert(来源:文档):T{
//一种方法,但需要将type属性添加到
//文档,即使我显式地尝试创建子类型。
//如果存在嵌套元素,也会出现问题,例如这些元素
//还需要type属性。
val mapper:ObjectMapper=SerializationUtils.buildJacksonObjectMapper()
返回mapper.convertValue(源代码,T::class.java)
//导致堆栈溢出
val mongoTemplate:mongoTemplate=applicationContext.getBean(mongoTemplate::class.java)
返回mongoTemplate.converter.read(T::class.java,源代码)
}
}
当存在_class属性时,我可以获得要使用的默认转换器行为吗?或者如何设置转换器,使其在知道子类型时不认为需要使用自定义转换器
弹簧靴2.4
Kotlin 1.4.32
SpringDataMongo3.1