简体   繁体   English

在Jersey中将复杂对象注入资源方法

[英]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功能解决。

  1. The general approach would be to create a class for each incoming type you need to support. 一般方法是为您需要支持的每种传入类型创建一个类。 Ex. 防爆。 SomeType1 , SomeType2 , SomeType3 `. SomeType1SomeType2SomeType3`
  2. All of these classes should extend the SomeType parent class. 所有这些类都应扩展SomeType父类。
  3. The SomeType parent class should have a CustomDeserializer . SomeType父类应具有CustomDeserializer
  4. In the CustomDeserializer you can inspect the json fields to determine what type the json should be deserialized to. CustomDeserializer中,您可以检查json字段以确定应将json反序列化为哪种类型。
  5. Then you can use the JsonParser.readValueAs method to deserialize the json into the desired type SomeType1 , SomeType2 , or SomeType3 . 然后,您可以使用JsonParser.readValueAs方法将json反序列化为所需的类型SomeType1SomeType2SomeType3
  6. 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. 如果您需要从数据库中获取更多数据并填充SomeType1SomeType2SomeType3的字段, 可以在处理程序中通过检查对象类型来做到这一点。

     @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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM