java - 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
有什么帮助吗?谢谢!
解决方案
看起来你想要多态序列化/反序列化。您应该查看 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);
}
}
推荐阅读
- python - 空闲python Mac上的ffmpeg
- python-3.x - 如何解决这个 python 代码错误:TypeError: object of type 'int' has no len()
- javascript - 未捕获的 ReferenceError:未定义 notifySuccess
- android - 浮动操作按钮不显示矢量资产
- php - 在一行中回显
- sql - ORACLE 选择查询,按大小写 ASC 和 DESC 排序
- php - 遇到错误严重性:非法字符串偏移 Codeigniter
- javascript - 如果在 Click 事件 Javascript 中声明
- oracle - CURRVAL 和 NEXTVAL 默认值如何在 Oracle 11 中生成“ORA-0094: column not allowed here”
- typescript - 如何使用 TypeScript 重用类构造函数参数作为文字字符串?