返回 ResponseEntity 与返回 POJO [英] Return ResponseEntity vs returning POJO
问题描述
我的应用程序基于带有一些 REST 端点的 Spring Boot.下面的 return 语句有什么区别吗?
My application is based on Spring Boot with some REST endpoints. Is there any difference between below return statements?
返回新的ResponseEntity
(myBean, HttpStatus.OK)
return myBean;
是否有任何最佳实践指南或任何技术差异?
Is there any best practice guidelines or any technical difference?
推荐答案
ResponseEntity
表示整个 HTTP 响应.除了 body 之外,它的 API 还允许您为响应设置 headers 和 状态代码.
ResponseEntity<T>
represents the entire HTTP response. Besides the body, its API allows you to set headers and a status code to the response.
只返回一个 bean 很好,但不会给你太多的灵活性:将来,如果你需要在响应中添加一个 header 或修改状态代码,例如,你需要更改方法返回类型.
Returning just a bean is fine but doesn't give you much flexibility: In the future, if you need to add a header to the response or modify the status code, for example, you need to change the method return type.
有关返回值的更多详细信息,请参阅 Spring MVC 文档.
For more details on return values, refer to the Spring MVC documentation.
这篇关于返回 ResponseEntity 与返回 POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!