Search code examples
javajerseyjax-rsjava-ee-6

Is it possible to define a jax-rs service interface separated from its implementation (with eclipse and jersey)?


I don't know if the title is confusing, but let's say I have this interface:

@Produces(MediaType.APPLICATION_JSON)
@Path("/user")
public interface UserService {

    @GET
    @Path("/{userId}")
    public Response getUser(@PathParam("userId") Long userId);

}

Why when I try to implement a version Eclipse rewrites annotation for the overridden method but not for the class?

class UserServiceImpl implements UserService {

    @Override
    @GET
    @Path("/{userId}")
    public Response getUser(@PathParam("userId") Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

}

I was trying to create a standard definition for the restful web service and then having different implementations. Is something like this possible with standard jax-rs? Am I using wrong annotations by any chance?


Solution

  • You can use annotation inheritance only if you don't use any jax-rs annotation on the implementing class: it is stated on section 3.6 of JSR-339.

    You redefine @Path and @Produces for the method but not for the class.

    So the Path annotation in your code should be on the concrete class:

    public interface UserService {
    
        @GET
        @Path("/{userId}")
        @Produces(MediaType.APPLICATION_JSON)
        public Response getUser(@PathParam("userId") Long userId);
    
    }
    
    
    @Path("/user")
    class UserServiceImpl implements UserService {
    
        @Override
        @GET
        @Path("/{userId}")
        @Produces(MediaType.APPLICATION_JSON)
        public Response getUser(@PathParam("userId") Long userId) {
            // TODO Auto-generated method stub
            return null;
        }
    
    }
    

    BTW, the specification encourages us to replicate the annotations on the concrete classes:

    For consistency with other Java EE specifications, it is recommended to always repeat annotations instead of relying on annotation inheritance.