我想知道在 dropwizard 中是否可以从不同的资源类调用另一个资源方法类。
我查看了其他帖子,使用 ResourceContext 允许从另一个资源类调用 get 方法,但也可以使用另一个资源类的 post 方法。
假设我们有两个资源类 A 和 B。在 A 类中,我创建了一些 JSON,我想使用 B 的 post 方法将该 JSON 发布到 B 类。这可能吗?
最佳答案
是的,资源上下文可用于从相同或不同资源中的另一个方法访问 POST
和 GET
方法。
借助@Context
,您可以轻松访问这些方法。
@Path("a")
class A{
@GET
public Response getMethod(){
return Response.ok().build();
}
@POST
public Response postMethod(ExampleBean exampleBean){
return Response.ok().build();
}
}
您现在可以通过以下方式从资源 B
访问资源 A
的方法。
@Path("b")
class B{
@Context
private javax.ws.rs.container.ResourceContext rc;
@GET
public Response callMethod(){
//Calling GET method
Response response = rc.getResource(A.class).getMethod();
//Initialize Bean or paramter you have to send in the POST method
ExampleBean exampleBean = new ExampleBean();
//Calling POST method
Response response = rc.getResource(A.class).postMethod(exampleBean);
return Response.ok(response).build();
}
}
关于java - Dropwizard资源类调用另一个资源方法类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430666/