繁体   English   中英

通过JAX-RS中的方法重写类中的@Path批注

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

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

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

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

但是,它隐含在类的@Path注释中。 例如

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

这是我的服务班级:

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

}

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

请注意以下几点:

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

但是,您是否考虑过使用其他资源类?

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

有关资源的更多详细信息,请参阅文档

您只需将方法的@Path注释更改为:

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

这样,连接类和方法@Path批注的结果路径将产生您所需的路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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