Jossef Harush Jossef Harush - 7 months ago 52
Java Question

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. e.g.

/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?

Answer

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.