简体   繁体   中英

Overriding a @Path annotation in a class by method in JAX-RS

I have a REST API service i maintain in java (over jersey, JAX-RS)

I want to support the following route in my service:

/api/v1/users/{userId}/cars

however, it concatinates to the class's @Path annotation. eg

/api/v1/cars/api/v1/users/{userId}/cars

This is my service class:

@Path("api/v1/cars")
public class CarsService {
    @GET
    @Path("/api/v1/users/{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        // ...
    }

    @GET
    public Response getCars() {
        // ...
    }

}

Is there any way to override it?

Note the following:

  • The @Path annotation in a class designates a root resource .
  • The @Path annotation in a method designates a sub-resource of a root resource .

When placed on methods, the @Path annotation does not override the @Path annotation of the class. JAX-RS/Jersey performs a hierarchical matching using the @Path annotations.

So, you can try:

@Path("api/v1")
public class CarsService {

    @GET
    @Path("/cars")
    public Response getCars() {
        ...
    }

    @GET
    @Path("/users/{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        ...
    }
}

However, have you considered using different resource classes?

@Path("api/v1/cars")
public class CarsService {

    @GET
    public Response getCars() {
        ...
    }
}
@Path("api/v1/users")
public class UsersService {

    @GET
    @Path("{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        ...
    }
}

For more details on resources, have a look at the documentation .

You just should change the @Path annotation of the method to:

@Path("users/{userId}/cars")

In this way, the resulting path of concatenating the class and the method @Path annotations will produce your desired path.

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