有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

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


共 (1) 个答案

  1. # 1 楼答案

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

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

    现在,您可以通过以下方式从Resource B访问Resource 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();
        }
    }