通过 JAX-RS 中的方法覆盖类中的 @Path 注释

Jos*_*ush 1 java jersey

我有一个用 java 维护的 REST API 服务(在球衣上,JAX-RS)

我想在我的服务中支持以下路线:

/api/v1/users/{userId}/cars
Run Code Online (Sandbox Code Playgroud)

但是,它连接到类的@Path注释。例如

/api/v1/cars/api/v1/users/{userId}/cars
Run Code Online (Sandbox Code Playgroud)

这是我的服务类:

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

}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以覆盖它吗?

cas*_*lin 5

请注意以下事项:

  • @Path一个注解指定一个根资源
  • 所述@Path在一个注释方法表示一个根资源的子资源

当放置在方法上时,@Path注解不会覆盖@Path类的注解。JAX-RS/Jersey 使用@Path注释执行分层匹配。

所以,你可以试试:

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

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

    @GET
    @Path("/users/{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,您是否考虑过使用不同的资源类?

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

    @GET
    public Response getCars() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)
@Path("api/v1/users")
public class UsersService {

    @GET
    @Path("{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

有关资源的更多详细信息,请查看文档