在编写 RestController 层的代码时,由于数据实体类定义了接口及实现类,本着面向接口编程的原则,我使用了接口作为 RestController 方法的入参。

代码大致如下(省略具体业务部分):

(1)模型接口:

 View Code

(2)模型实现类

 View Code

(3)RestController POST接口代码

 View Code

(4)前台用的axios发送的请求代码

 View Code

 

但在运行测试时发现 Spring boot 本身的默认中并不支持将interface或抽象类作为方法的参数。报了如下错误:

复制代码
2019-09-08 19:32:22.290 ERROR 12852 --- [nio-9999-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    
: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException:
Type definition error: [simple type, class com.sample.demo.model.User]; nested exception is com.fasterxml.jackson.databind
.exc.InvalidDefinitionException: Cannot construct instance of `com.sample.demo.model.User` (no Creators, like default
construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer,
or contain additional type information at [Source: (PushbackInputStream); line: 1, column: 1]] with root cause
...
复制代码

大致意思时不存在创建实例的构造函数,抽象类型需要配置映射到具体的实现类。

 

解决方案一:

于是我上网搜了下解决方法,最终在 

@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 {  }

通过添加注解的方式,将接口映射到实现类。