restful service interface with jersey

Aravind Datta picture Aravind Datta · Nov 22, 2013 · Viewed 10.2k times · Source

Can I create a restful service with interface and implementation class?

If so, will all JAX-RS related imports go into the interface?

I am using jersey2.4 and jetty8.1.

Here is my MyService interface:

package foo.bar; 

@Path("/abc")
public interface MyService {

     @GET
     @JSONP
     @Path("/method/{id}")
     public MyResponse getStuff(@PathParam("id") Integer id);

}

And an implementation of MyServiceImpl that interface

package foo.bar.impl;

public class MyServiceImpl implements MyService {

     public MyServiceImpl() {}

     @Override
     public MyResponse getStuff(Integer id) {
         // do stuff
         return MyResponse;
     }
}

Here's the web.xml file:

<servlet>
    <servlet-name>Scivantage REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>foo.bar</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

I registered this service provider package (foo.bar) but it complains saying this

javax.servlet.ServletException: A MultiException has 1 exceptions.  They are:|1. java.lang.NoSuchMethodException: Could not find a suitable constructor in foo.bar.MyService class.

When I tried with implementation class package (foo.bar.impl), it complains saying this

I get HTTP ERROR 404; doesn't do anything else; no exceptions on console

When I tried both -- it complains the same as above:

javax.servlet.ServletException: A MultiException has 1 exceptions.  They are:|1. java.lang.NoSuchMethodException: Could not find a suitable constructor in foo.bar.MyService class.

What I am doing wrong?

Answer

Jiaji Wu picture Jiaji Wu · Oct 13, 2014

Here's a solution I came across after a few trials (I'm working with jetty 9 and jersey 2.13): instead of annotate the interface (with @Path("/abc")), try to annotate the implementation class instead.

I think this makes good sense since interface are 'abstract' and not supposed to be bound to physical paths. This way, the interface can be reused in different paths.