Use the interface in the argument of the Spring method of the controller

I have two classes Aand Bthat implement an 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();
}

I want to use one controller method that can work on both A and B depending on which object the external interface sends. So when I try to use the interface, Spring complains that no suitable message converter was found.

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

, 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:'My name'} {type:'B', myCustomclass:{....}}

:

Spring MVC @RequestBody

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

Spring @RequestBody, ( )

+2

Object ?

public String updateRecord(@RequestBody Object obj,..

public String updateRecord(@RequestBody T obj,.. // I am not sure for this

instanceOf .

0

spring/jackson , json . . , . , jsonTypeinfo .. , . Spring MVC @ModelAttribute/@RequestParam

0

Source: https://habr.com/ru/post/1672969/


All Articles