问题
I was wondering if it was possible in dropwizard to call another resource method class from a different resource class.
I looked around other posts and using ResourceContext allows one to call a get method from another resource class, but it also possible to use a post method from another resource class.
Let say we have two resource classes A and B. In class A, I have created some JSON and I want to post that JSON to B class using B's post method. Would that be possible?
回答1:
Yes, Resource Context can be used to access both POST and GET methods from another method in same or different resource.
With the help of @Context, you can easily access the methods.
@Path("a")
class A{
@GET
public Response getMethod(){
return Response.ok().build();
}
@POST
public Response postMethod(ExampleBean exampleBean){
return Response.ok().build();
}
}
You can now access the methods of Resource A from Resource B in the following manner.
@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();
}
}
来源:https://stackoverflow.com/questions/40430666/dropwizard-resource-classes-calling-another-resource-method-classes