Robert Strauch
Robert Strauch

Reputation: 12896

Generalize Spring REST controller for similar methods

In a Spring Boot application, there are two rest endpoints for different resources but their implementation is almost identical. Please see the following examples.

Resource 1:

@GetMapping(path = "/resource-1/{name}", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomResponse> getResource1(@PathVariable("name") String name) {
    try {
        return ResponseEntity.ok(myService.getResource1(name));
    } catch (EntityNotFoundException e) {
        return status(NOT_FOUND).build();
    } catch (Exception e) {
        return status(INTERNAL_SERVER_ERROR).build();
    }
}

Resource 2:

@GetMapping(path = "/resource-2/{name}", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomResponse> getResource2(@PathVariable("name") String name) {
    try {
        return ResponseEntity.ok(myService.getResource2(name));
    } catch (EntityNotFoundException e) {
        return status(NOT_FOUND).build();
    } catch (Exception e) {
        return status(INTERNAL_SERVER_ERROR).build();
    }
}

As you can see, the methods only differ in the called service method depending on the resource path resource-1 or resource-2.

Is there any "Spring Boot"-ish way to reduce this duplicate code and put it in a more generic method?

Upvotes: 1

Views: 170

Answers (1)

omar jayed
omar jayed

Reputation: 868

This worked for me

@GetMapping(path = "/resource-{var}/{name}", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomResponse> getResource(@PathVariable ("var") int var, @PathVariable("name") String name) {
    // do according to the var value
}

Upvotes: 3

Related Questions