首页 > 解决方案 > Spring建模:字段作为接口

问题描述

有没有办法将一个字段作为接口放在文档的模型中?例子:

public class Foo {
    private String id;
    private Bar bar;
}

Bar具有多个实现的接口在哪里。Bar 内部有一个方法签名String getType(),它告诉我可以使用哪个实现来映射数据库中的数据。

我尝试了不同的解决方案(@ReadingConverter/ @WiritingConverter@JsonSerialize/ @JsonDeserialize)但没有结果。每次我得到

Failed to instantiate [Bar]: Specified class is an interface

有什么帮助吗?谢谢!

标签: javamongodbspring-data-mongodb

解决方案


看起来你想要多态序列化/反序列化。您应该查看 Jackson 文档:http ://www.baeldung.com/jackson-advanced-annotations

简而言之,您需要做这样的事情,其中@JsonTypeIdResolver​​注释用于定义自定义类型解析器:

@JsonTypeInfo(use = @JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.PROPERTY, 
    property = "@type"
)
@JsonTypeIdResolver(BarTypeIdResolver.class)
public interface Bar {
    ...
}

public class BarTypeIdResolver extends TypeIdResolverBase {
    // boilerplate skipped, see the documentation
     
    @Override
    public String idFromValueAndType(Object obj, Class<?> subType) {
        String typeId = null;
        if (obj instanceof Bar) {
            Bar bar = (Bar) obj;
            typeId = bar.getType();
        }
        return typeId;
    }
 
    @Override
    public JavaType typeFromId(DatabindContext context, String id) {
        Class<?> subType = null;
        switch (id) {
        case "barImpl1":
            subType = BarImpl1.class;
            break;
            ...
        }
        return context.constructSpecializedType(superType, subType);
    }
}

推荐阅读