java - 在 Spring Controller 方法参数中使用接口(interface)

标签 java spring spring-mvc model-view-controller

我有两个类 AB 正在实现一个接口(interface)。

public class A implements MyInterface {

    // Class A stuff
  private String name;

  public String getName() {
   return name;
  }

  public void setName(String name) {
this.name = name;
 }
}

public class B implements MyInterface { 
    //Class B stuff

   private MyCustomClass myCustomclass;

   public String getName() {
    this.myCustomclass.getName();
 }
}


public interface MyInterface {

  public String getName();
}

我想使用一个 Controller 方法,它可以在 A 和 B 上工作,具体取决于前端发送的对象。因此,当我尝试使用接口(interface)时,Spring 提示找不到合适的消息转换器。

@RequestMapping(value = "/mymethod", method = RequestMethod.POST) 
public String updateRecord(@RequestBody MyInterface myInterface, HttpServletResponse response) { 
        //Do stuff
}

最佳答案

Jackson 可以确定使用哪个实现序列化为 JSON,但无法确定使用哪个实现反序列化 JSON。对于序列化,它需要做的就是调用 getClass() 并为该类型构建一个序列化程序。但是在反序列化时(目前)没有这样的类型信息。您应该使用 Jackson 注释 @JsonTypeInfo@JsonSubTypes 来实现多态 json。

@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = A.class, name = "A"),
        @JsonSubTypes.Type(value = B.class, name = "B")})
public interface MyInterface {

}

那么请求体myInterface一定是,

{type:'A', name:'我的名字'}{type:'B', myCustomclass:{....}}

引用这三个:

Spring MVC @RequestBody into an Interface instead of a class

https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

Spring @RequestBody containing a list of different types (but same interface)

关于java - 在 Spring Controller 方法参数中使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965921/

相关文章:

java - Spring 添加监听器作为组件而不是通过构造函数

java - 使用 Spring MVC 3.1.2 重定向

Tomcat-Maven 401 错误 : Cannot invoke Tomcat manager

java - 如何在 Mac 上使用 SceneBuilder 和 IntelliJ

java - 尝试使用 Java 打印文件内容时获取垃圾字符

java - 非法参数异常 : defaultTarget must start with '/' or with 'http(s)'

java - POST 请求显示 "405 GET not supported"并启用了 Spring 安全性

java - 如何在android中的Cloud Firestore中修补JSON?

java - Spring 入站文件 channel 适配器 Prevent-duplicates=false 不起作用

java - 如何修复 "InvalidImageSize","message":"Image size is too small."