My application is based on Spring Boot with some REST endpoints. Is there any difference between below return statements?
return new ResponseEntity<MyBean>(myBean, HttpStatus.OK)
return myBean;
Is there any best practice guidelines or any technical difference?
A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.
ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.
Yes, Service returning domain object should be preferable to a Service returning ResponseEntity<> . There is no best practices. Having said that, you should think of implementing something like Hexagonal or Layered architecture.
ResponseEntity<T>
represents the entire HTTP response. Besides the body, its API allows you to set headers and a status code to the response.
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.
For more details on return values, refer to the Spring MVC documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With