Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey @Path annotation mandatory at class level

Tags:

java

rest

jersey

I have a class like:

public class TestService {

@Path("/v1/test1/list")
    public Response getTest1() {
}

@Path("/v1/test2/list")
    public Response getTest2() {
}

}

If I do not give @Path annotation at Class level, then this class is not recognized as a REST resource, but I cannot give "/v1" Path for this class since there is already another class with @Path("/v1").

What are possible workaround, to make this class to be recognized as a Rest Resource

like image 300
user1933888 Avatar asked Aug 31 '16 00:08

user1933888


1 Answers

Resource classes

A @Path annotation is required to define a resource class. Quoting the Jersey documentation:

Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path, have at least one method annotated with @Path or a resource method designator annotation such as @GET, @PUT, @POST, @DELETE.

One possible solution

As already mentioned by Justas, one possible solution is to add the @Path("") annotation to the TestService class. However, it doesn't smell good:

@Path("")
public class TestService {

    @GET
    @Path("/v1/test1/list")
    public Response getTest1() {
        ...
    }

    @GET
    @Path("/v1/test2/list")
    public Response getTest2() {
        ...
    }
}

A better solution

I don't know what your project looks like, but instead of having a single class, I would have two classes, designed as following:

@Path("/v1/test1")
public class TestService1 {

    @GET
    @Path("/list")
    public Response getTest1() {
        ...
    }
}
@Path("/v1/test2")
public class TestService2 {

    @GET
    @Path("/list")
    public Response getTest2() {
        ...
    }
}
like image 117
cassiomolin Avatar answered Sep 22 '22 21:09

cassiomolin