【问题标题】:Spring ReST controller: how to avoid methods with same RequestParamsSpring ReST 控制器:如何避免具有相同 RequestParams 的方法
【发布时间】:2016-11-07 13:49:27
【问题描述】:

在 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 的代码重复?

【问题讨论】:

  • 使用一个对象来绑定。

标签: spring spring-boot


【解决方案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

【讨论】:

  • 这似乎是一个不错的解决方案 :-) 有没有办法方便地检查 required-Constraint 是否满足(如果有 @RequestParams 属性为 required=true
【解决方案2】:

您可以定义名为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
}

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多