如何使用@PathParam的自定义类型? [英] How to use Custom type for @PathParam?

查看:944
本文介绍了如何使用@PathParam的自定义类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用非spring bean类对象作为jersey web服务类方法的参数。但它在构建时给出了缺少的依赖性错误。

I want to use non spring bean class object as parameter for jersey web service class method. But it is giving missing dependency error at build time.

我的代码是:

@Component
@Path("/abcd")
public class ActorServiceEndpoint {

    @POST
    @Path("/test/{nonspringBean}")
    @Produces(MediaType.APPLICATION_XML)
    public void addActor(@PathParam("nonspringBean") MyNonSpringBeanClass nonspringBean){
}

}


推荐答案

东西是路径参数以String形式出现。根据规范,如果我们希望将自定义类型注入为 @PathParam ,则自定义类应该具有以下三种之一:

The thing is path parameters come in String form. As per the specification, if we want the have a custom type be injected as a @PathParam, the custom class, should have one of three things:


  1. 公共静态 valueOf(String param)返回类型

  2. 公共静态 fromString(String param)返回类型

  3. 或接受字符串的公共构造函数

  4. 另一个选项实现 ParamConverter 。您可以看到一个示例这里

  1. A public static valueOf(String param) that returns the type
  2. A public static fromString(String param) that returns the type
  3. Or a public constructor that accepts a String
  4. Another option implement a ParamConverter. You can see an example here.

如果你不拥有这个课程(这是第三个 - 你不能改变的派对类)那么你唯一的选择就是使用 ParamConverter / ParamConverterProvider 对。

If you don't own the class (it's a third-party class that you can't change) then your only option is to use the ParamConverter/ParamConverterProvider pair.

在任何一种情况下,您都需要通过在构造函数中或在上述方法之一中解析String来相应地构造实例。执行此操作后,可以使用注释将自定义类型设置为方法参数。

In either of these cases you'll want to construct the instance accordingly by parsing the String either in the constructor or in one of the above mentioned methods. After doing this, the custom type can be made a method parameter with the annotation.

其他参数也是如此,例如 @FormParam @HeaderParam @QueryParam 等。

The same holds true for other params, such as @FormParam, @HeaderParam, @QueryParam, etc.

这篇关于如何使用@PathParam的自定义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆