将 Spring REST 控制器概括为类似方法

Generalize Spring REST controller for similar methods

在 Spring 引导应用程序中,有两个用于不同资源的剩余端点,但它们的实现几乎相同。请看下面的例子。

资源 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();
    }
}

资源 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();
    }
}

如您所见,根据资源路径resource-1resource-2.

,方法仅在调用的服务方法上有所不同

是否有任何类似“Spring Boot”的方法来减少此重复代码并将其放入更通用的方法中?

这对我有用

@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
}