Spring ResponseEntity用于可选

时间:2018-07-06 10:13:28

标签: spring spring-web

我经常在代码中使用的构造如下:

@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上实现这种方法是一个好主意吗?

1 个答案:

答案 0 :(得分:0)

我知道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());
 }