[英]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) 我有一个用Java维护的REST API服务(球衣,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. 但是,它隐含在类的
@Path
注释中。 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: 请注意以下几点:
@Path
annotation in a class designates a root resource . @Path
在类注释指定一个根资源 。 @Path
annotation in a method designates a sub-resource of a root resource . @Path
的方法中的注释表示一个根资源的子资源 。 When placed on methods, the @Path
annotation does not override the @Path
annotation of the class. 当放置在方法上时,@
@Path
注释不会覆盖类的@Path
注释。 JAX-RS/Jersey performs a hierarchical matching using the @Path
annotations. JAX-RS / Jersey使用
@Path
注释执行分层匹配。
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注释更改为:
@Path("users/{userId}/cars")
In this way, the resulting path of concatenating the class and the method @Path annotations will produce your desired path. 这样,连接类和方法@Path批注的结果路径将产生您所需的路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.