How to register a static class in Jersey?

蓝咒 提交于 2019-12-12 12:11:57

问题


I have a class of which only static methods are to be accessed via @path annotations and which does not have a public constructor. My simpilified program is:

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

Running and calling "time" gives me the following error:

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.

回答1:


Sorry, according to the JSR, paragraph 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.

You can use the Adapter design pattern and create JAX-RS resource (POJO with @Path) which simply delegates to your static class. This would be very easy to understand for those coming behind you.




回答2:


The @Path annotation is designed to define a resource at the class level. The method to execute isn't controlled by @Path, but by @GET, @POST, @PUT, @HEAD, etc... with @GET as the desired operation in your case.

Your class for the "time" resource should look like this:

@Path("/time")
public class TimeResource { 
    @GET
    public static String time(){
        return Instant.now().toString();
    }
}

You could theoretically define each function as a static nested class within one "main" class:

public class MyResource{

    @Path("/time")
    public static final class TimeResource {    
        @GET
        public static String do(){
            return Instant.now().toString();
        }
    }

    @Path("/doSomethingElse")
    public static final class DoSomethingElseResource { 
        @GET
        public static String do(){
            // DO SOMETHING ELSE
        }
    }       
}

Though I don't know if that would work, you'd have to try it. I don't think there's much advantage in having them all in one class like that, though.



来源:https://stackoverflow.com/questions/26549005/how-to-register-a-static-class-in-jersey

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!