1

In a Spring ReST Controller class, there are three methods with identical @RequestParams, but different RequestMappings and behavior, like in the following (simplified) example:

@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
    ) { ...}

Is there a way to avoid code duplication concerning the @RequestParam's?

Mr.Radar
  • 775
  • 1
  • 11
  • 32

2 Answers2

1

Replace them with a single object.

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) { ... }

See also How to bind @RequestParam to object in Spring MVC.

Community
  • 1
  • 1
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
  • That seems to be quite a nice solution :-) Is there a way to conveniently check if the `required`-Constraint is fulfilled (in case there are `@RequestParams` with attribute `required=true`) – Mr.Radar Nov 07 '16 at 14:06
  • 1
    [Spring MVC: How to perform validation?](http://stackoverflow.com/q/12146298/476716) – OrangeDog Nov 07 '16 at 14:07
0

You can define parent type called MyResponse and then you can use ResponseEntity as shown below:

@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 class API shown below:

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
}
Vasu
  • 21,832
  • 11
  • 51
  • 67