[英]Passing an interface implementation as a Spring @RequestBody argument
I have the the following classes: 我有以下课程:
public class ItemController implements ApiController<Item> {
@RequestMapping(value = "/", method = RequestMethod.POST)
public Item create(@RequestBody final CreateItemRequest request) {
// ...
}
}
public interface ApiController<T> {
T create(@RequestBody final ApiRequest request);
}
public class CreateItemRequest implements ApiRequest {
// ...
}
public interface ApiRequest {
// ...
}
I'm warned by Intellij that ItemController
does not implement ApiController
. Intellij警告我
ItemController
不实现ApiController
。 My working assumption is that CreateItemRequest
, as an implementation of ApiRequest
, is a valid type for the signature of the create
method as it's written above. 我的工作假设是,作为
ApiRequest
的实现, CreateItemRequest
是上面所写的create
方法签名的有效类型。 However, Intellij insists that the type of the request
parameter should be ApiRequest
. 但是,Intellij坚持
request
参数的类型应为ApiRequest
。
My goal here is to have a common interface for classes like CreateItemRequest
to implement. 我的目标是为诸如
CreateItemRequest
类的类实现一个通用接口。 That interface would be referred to in a generic-y sort of way within ApiController
methods. 该接口将在
ApiController
方法中以通用Y方式进行ApiController
。
Obviously, I'm not a generics wizard, so what have I mixed up here? 显然,我不是泛型向导,所以我在这里混了什么?
edit: ThingRequest
properly implements ApiRequest
. 编辑:
ThingRequest
正确实现ApiRequest
。
Update: 更新:
You can not narrow method parameters while implementing an interface! 实现接口时,不能缩小方法参数! - The
-的
You have an interface ApiController<T>
with the method T create(final ApiRequest request)
. 您有一个
interface ApiController<T>
,它的方法为T create(final ApiRequest request)
。 This interface tells a client that he can invoke the method create
with ANY!!! 该接口告诉客户端,他可以调用ANY
create
的方法!!! class that implements ApiRequest
, therefore it is not allowed to have a implementation of ApiController
that restrict the argument type of create
to CreateItemRequest
!! 实现类
ApiRequest
,因此不允许有一个实现ApiController
制约的参数类型create
于CreateItemRequest
!
old answer: 旧答案:
You wrote: 你写了:
public interface ApiController<T> {
T create(@RequestBody final ApiRequest request);
}
and 和
public class ItemController implements ApiController<Item> {
@RequestMapping(value = "/", method = RequestMethod.POST)
public Thing create(@RequestBody final CreateItemRequest request) {
// ...
}
}
One problem is the method argument, the problem is the return type! 一个问题是方法参数, 问题是返回类型!
Thing
is not Item
! Thing
不是Item
!
OK you told that this is an typo, so read the update above 好的,您告诉我们这是错字,所以请阅读上面的更新
BTW: I strongly recommend to add the @Override
annotation to methods that implement/override other methods 顺便说一句:我强烈建议将
@Override
注释添加到实现/重写其他方法的方法中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.