【发布时间】: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-1 或resource-2。
是否有任何“Spring Boot”式的方法来减少这种重复代码并将其放入更通用的方法中?
【问题讨论】:
标签: spring spring-boot spring-restcontroller