简体   繁体   中英

Jersey @Path annotation mandatory at class level

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

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() {
        ...
    }
}

You can add empty path @Path("") or @Path("/") . However, this problem may show that you should design your code differently.

The @Path annotation is used to specify the URI through which a resource and an API can be accessed. Resource in this case is the REST Web service itself. Thus this annotation is present at the class level as well as the method level. It is mandatory to annotate a REST Web resource class with the @Path annotation. Thus if a user wants to access the 'Countries' through the resource 'HelloWorld' context, then:

Resource at the class level would have @Path("/") . This is the default annotation at the class level. Resource at the API level would have @Path("Countries") annotation. As a best practice, the class-level path annotation should be a noun that qualifies the Web service, and the method-level annotation can be a noun or an action (for example, user and add-user, respectively).

https://www.juniper.net/documentation/en_US/junos-space-sdk/13.1/apiref/com.juniper.junos_space.sdk.help/html/reference/spaceannoREST.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM