Dropwizard 资源类调用另一个资源方法类?

Bob*_*ob 1 java json dropwizard

我想知道在 dropwizard 中是否可以从不同的资源类调用另一个资源方法类。

我查看了其他帖子,使用 ResourceContext 允许从另一个资源类调用 get 方法,但也可以使用来自另一个资源类的 post 方法。

假设我们有两个资源类 A 和 B。在类 A 中,我创建了一些 JSON,我想使用 B 的 post 方法将该 JSON 发布到 B 类。那可能吗?

Pri*_*pta 6

是的,资源上下文可用于从相同或不同资源中的另一个方法访问POSTGET方法。
借助@Context,您可以轻松访问这些方法。

@Path("a")
class A{
    @GET
    public Response getMethod(){
        return Response.ok().build();
    }
    @POST
    public Response postMethod(ExampleBean exampleBean){
        return Response.ok().build();
    }
}
Run Code Online (Sandbox Code Playgroud)

您现在可以通过以下方式访问Resource AfromResource B的方法。

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)