【问题标题】:Generalize Spring REST controller for similar methods为类似方法泛化 Spring REST 控制器
【发布时间】:2021-03-29 07:57:06
【问题描述】:

在 Spring Boot 应用程序中,有两个用于不同资源的 rest 端点,但它们的实现几乎相同。请参阅以下示例。

资源 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”式的方法来减少这种重复代码并将其放入更通用的方法中?

【问题讨论】:

    标签: spring spring-boot spring-restcontroller


    【解决方案1】:

    这对我有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2021-03-23
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多