我经常在代码中使用的结构如下:
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
Optional<Message> message = helloService.getMessage();
if (message.isPresent()) {
return ResponseEntity.ok(message.get());
}
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
}
遵循 DRY 原则,我将这个结构抽象出来;
private <T> ResponseEntity<T> response(Optional<T> value) {
if (value.isPresent()) {
return ResponseEntity.ok(value.get());
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
这样我的代码就变成了;
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
return response(helloService.getMessage());
}
如果这个构造是 Spring 的 ResponseEntity 类的一部分,那么我的代码就变成了;
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
return ResponseEntity.optional(helloService.getMessage());
}
你认为在 ResponseEntity 上实现这样的方法是个好主意吗?
最佳答案
我知道 OP 要求 NO_CONTENT 响应,但如果你在 NOT_FOUND 之后,你有一个自 Spring 5.1 以来的便捷方法 - ResponseEntity.of()
:
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
return ResponseEntity.of(helloService.getMessage());
}
如果您需要 NO_CONTENT,我可以建议以下内容稍微不那么冗长: @GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
return helloService.getMessage()
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.noContent().build());
}
关于可选的 Spring ResponseEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51208090/