如何在Jersey中注册静态类?

我有一个类,其中只有静态方法可以通过@path注释访问,并且没有公共构造函数.我的简化计划是:

@Path("")
static class MyStaticClass
{
  private MyStaticClass() {...}
 @Get @Path("time")
  static public String time()
  {
     return Instant.now().toString();
  }
}

运行并调用“时间”会给我以下错误:

WARNUNG: The following warnings have been detected: WARNING: HK2 service reification failed for [...] with an exception:
MultiException stack 1 of 2
java.lang.NoSuchMethodException: Could not find a suitable constructor in [...] class.

解决方法:

对不起,根据JSR第3.1.2段

Root resource classes are instantiated by the JAX-RS runtime and MUST
have a public constructor for which the JAX-RS runtime can provide all
parameter values. Note that a zero argument constructor is permissible
under this rule.

您可以使用Adapter design pattern并创建JAX-RS资源(带有@Path的POJO),它只是委托给您的静态类.对于那些落伍的人来说,这很容易理解.

上一篇:java – Spring-boot jersey:资源不能自动发现


下一篇:java – 为什么我在执行POST请求时得到405方法不允许