[英]Inject complex object into resource method in Jersey
I'm working on a RESTful service in Java 8. I have the following method in my resource class, which responds to POST
requests. 我正在使用Java 8开发RESTful服务。我的资源类中具有以下方法,该方法可响应
POST
请求。
@POST
public Response store(SomeType myInstance){ ... }
Typically, this get's deserialised without a hitch in case the json
request can be directly mapped. 通常,在可以直接映射
json
请求的情况下,可以轻松进行此序列化。 However, SomeType
in this case is a complex object containing other objects persisted in a database. 但是,在这种情况下,
SomeType
是一个复杂的对象,其中包含持久保存在数据库中的其他对象。
Is there a way to capture the request, figure out the type, build the object SomeType
and then pass it through to the store
method? 有没有一种方法可以捕获请求,弄清楚类型,构建对象
SomeType
,然后将其传递给store
方法? I'm leaning towards some type of middleware, yet I'm not quite sure how the dependencies would work. 我倾向于某种类型的中间件,但是我不太确定依赖项将如何工作。
Note: For security reasons, I am very limited in 3rd party packages that I can use. 注意:出于安全原因,我在可以使用的第三方包装中非常有限。 So I can't use out of the box solutions.
所以我不能使用开箱即用的解决方案。
I think your use case can be solved with Jackson's CustomDeserializer feature. 我认为您的用例可以通过Jackson的CustomDeserializer功能解决。
SomeType
parent class should have a CustomDeserializer . SomeType
父类应具有CustomDeserializer 。 If you need to fetch some more data from a database and populate fields of SomeType1 , SomeType2 , and SomeType3 you can do that within your handler by checking the object type. 如果您需要从数据库中获取更多数据并填充SomeType1 , SomeType2和SomeType3的字段, 则可以在处理程序中通过检查对象类型来做到这一点。
@POST public Response store(SomeType myInstance) { if (myInstance instanceof SomeType1) { // fetch from database and populate more fields } else if (myInstance instanceof SomeType2) { ... } ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.