我有一个类,其中只能通过 @path
注释访问静态方法,并且没有公共(public)构造函数。我的简化程序是:
@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),它只是委托(delegate)给您的静态类。这对于后面的人来说很容易理解。
关于java - 如何在 Jersey 中注册一个静态类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26549005/