我试图将多个相似的文档存储在同一个文档存储(MongoDB)中,即扩展 Foo 的所有类都存储在 Foo 集合中。
我有一个名为 findById 的休息端点,它返回一种可选类型,例如/foo/{id}.
当我调试它时,它返回一个 Bar 类(它扩展了 Foo
但是,当我从 java 客户端应用程序调用它时。
Foo 类
@Data
@Document(collection = "foo")
public abstract class Foo {
@Id
private int id;
public Foo(){}
public Foo(int id){
this.id = id;
}
酒吧类
@Document(collection = "foo")
@Data
public class Bar extends Foo{
private String text;
@PersistenceConstructor
public EnterValue(int id, String text){
super(id);
this.text = text;
}
@Override
public int getId() {
return super.getId();
}
@Override
public int setId(UUID id) {
super.setId(id);
}
public String getText(){
return this.text;
}
public void setText(String text) {
this.text = text;
}
客户端代码:
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Foo> response = restTemplate.exchange("http://localhost:8080/foo/123",HttpMethod.GET,entity,Foo.class);
提取类型 [class Foo] 和内容类型 [application/json;charset=UTF-8] 的响应时出现错误。
最佳答案
- 您放入 ResponseEntity 菱形运算符中的类型不能是抽象的;
- 它必须实现可序列化。
public class Bar extends Foo implements Serializable {
...
}
...
ResponseEntity<Bar> response = restTemplate.exchange("<a href="http://localhost:8080/foo/123" rel="noreferrer noopener nofollow">http://localhost:8080/foo/123</a>", HttpMethod.GET, entity, Bar.class);
关于Java Spring Rest Call使用父类(super class)获取子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56692999/