【问题标题】:Correct way to write ResponseEntity<T> with @RestController for Spring RESTful Api使用 @RestController 为 Spring RESTful Api 编写 ResponseEntity<T> 的正确方法
【发布时间】:2021-10-06 16:28:37
【问题描述】:
@RestController
public class TestController {
    @GetMapping(path = "/demo")
    public ResponseEntity<?> test() {
        User user = new User();
        user.setAge("12");
        HttpHeaders responseHeaders = new HttpHeaders();
        return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
    }
}

我查看了一些文档,发现有些人会这样写: rResponseEntity.ok().headers(responseHeaders).body(user);

new ResponseEntity&lt;&gt;(user, responseHeaders, HttpStatus.OK);ResponseEntity.ok().headers(responseHeaders).body(user); 有什么区别?首选哪种方式?谢谢。

【问题讨论】:

  • 没有推荐的方法 AFAIK,使用您喜欢的方法。第二个通过构建器可以说更容易阅读,但这是一个偏好问题。
  • 为什么我们可以写ResponseEntity.ok().headers(responseHeaders).body(user);?这里有逻辑支持吗?
  • 不,它只是跟随builder pattern.body(user) 最终调用new ResponseEntity&lt;&gt;(...)
  • 我更喜欢让方法直接返回类型(在您的示例中为User)并在出现问题时使用异常(例如ResponseStatusException)。但正如@sp00m 已经说过的那样,这真的是品味问题。
  • @slauth 如果我使用异常应该如何修改代码?谢谢。

标签: spring spring-boot spring-data-jpa


【解决方案1】:

我正在展示一个直接返回 User 的小示例,因为恕我直言,它会导致更清晰的签名:

@RestController
public class TestController {
    
    @GetMapping(path = "/demo")
    public User test() {
        if (userDoesNotExist()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        User user = new User();
        user.setAge("12");
        return user;
    }
}

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2014-11-01
    • 2018-03-14
    • 2017-11-02
    • 2018-10-30
    相关资源
    最近更新 更多