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

后端 未结 2 787
北恋
北恋 2020-12-14 02:52

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 UserSe         


        
相关标签:
2条回答
  • 2020-12-14 03:11

    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.

    0 讨论(0)
  • 2020-12-14 03:21

    I had a similar issue working with interface automatically generated using the OpenAPI generator. The problem here was that I couldn't easily remove the @Path annotation from the interface and additionally adding it to the class caused ambiguity issues.

    Problems with @Path-annotated interfaces however only occurs for resources that are automatically discovered on registered packages. For registered packages, all classes (and unfortunately interfaces as well) that are annotated with @Path will be instantiated.

    To prevent that, you can just register your resources manually with your ResourceConfig as in the following example:

    new ResourceConfig()
        .registerClasses(UserServiceImpl.class);
    

    Just make sure, your interfaces are not in a package that are registered with your ResourceConfig. Using this approach, you can use the implementation from your example and also the @Path annotation added to the interface will be interpreted correctly.

    Disclaimer: There probably should not be any @Path path annotation on the interface in the first place, but unfortunately this is what the OpenAPI generator creates. If you find yourself in a similar situation, I hope this helps. Otherwise, you should refer to the accepted answer.

    0 讨论(0)
提交回复
热议问题