Spring ReST控制器:如何避免具有相同RequestParams的方法

时间:2016-11-07 13:49:28

标签: spring spring-boot

在Spring ReST Controller类中,有三个方法具有相同的@RequestParams,但具有不同的RequestMappings和行为,如下面的(简化)示例所示:

@RequestMapping(method = GET, value = "/search")
    public MySearchResponse findAll(
            @RequestParam(required = false, value = "foo") String foo,
            @RequestParam(required = false, value = "bar") String bar,
            @RequestParam(required = false, value = "baz") Long baz,
            @RequestParam(required = false, value = "fooBar") Long fooBar
    ) { ...}

@RequestMapping(method = GET, value = "/export")
    public MyExportResponse exportAll(
            @RequestParam(required = false, value = "foo") String foo,
            @RequestParam(required = false, value = "bar") String bar,
            @RequestParam(required = false, value = "baz") Long baz,
            @RequestParam(required = false, value = "fooBar") Long fooBar
    ) { ...}

有没有办法避免有关@ RequestParam的代码重复?

2 个答案:

答案 0 :(得分:1)

用一个物体替换它们。

static class MyParmeters {
    String foo;
    String bar;
    Long baz;
    Long fooBar;
}

@RequestMapping(method = GET, value = "/search")
public MySearchResponse findAll(MyParmeters params) { ... }

@RequestMapping(method = GET, value = "/export")
public MyExportResponse exportAll(MyParameters params) { ... }

另见How to bind @RequestParam to object in Spring MVC

答案 1 :(得分:0)

您可以定义名为MyResponse的父类型,然后您可以使用ResponseEntity,如下所示:

@RequestMapping(method = GET, value = "/searchOrExport")
public ResponseEntity<MyResponse> exportAll(@RequestParam(required = false, value = "foo") String foo,
            @RequestParam(required = false, value = "bar") String bar,
            @RequestParam(required = false, value = "baz") Long baz,
            @RequestParam(required = false, value = "fooBar") Long fooBar) {
      //code to handle search and Export
}

Bean类API如下所示:

public abstract class MyResponse  {
    //any common properties add here
}


public class MySearchResponse implements MyResponse {
   //add MySearchResponse properties
}

public class MyExportResponse implements MyResponse {
   //add MyExportResponse properties
}