In Spring Webflux, what's the difference between ResponseEntity<Mono> versus Mono<ResponseEntity> as a return type of a rest controller?
When is the most appropriate to what?
Following up on this question, let's say I need to return a list, or let's say several elements of Foo, there are many examples of returning Flux. Would it make sense to return ResponseEntity<Flux> or Flux<ResponseEntity>?
When I'm looking for this question, I found the same question posted here: https://github.com/spring-projects/spring-framework/issues/22614, but no answer, I searched spring docs, but find no info.
Thanks for the help.
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.
A Mono is a stream of 0 to 1 element, whereas a Flux is a stream of 0 to N elements. This difference in the semantics of these two streams is very useful, as for example making a request to a http server expects to receive 0 or 1 response, it would be inappropriate to use a Flux in this case.
ResponseEntity<> is a generic class with a type parameter, you can specify what type of object to be serialized into the response body. @ResponseBody is an annotation, indicates that the return value of a method will be serialized into the body of the HTTP response.
Here are the various options you can make with a ResponseEntity
return value:
ResponseEntity<Mono<T>>
or ResponseEntity<Flux<T>>
-- this makes the response status and headers known immediately while the body is provided asynchronously at a later point. Whether the body is Mono
or Flux
depends on how many values the response has.Mono<ResponseEntity<T>>
-- this provides all three -- response status, headers, and body, asynchronously at a later point. IT allows the response status and headers to vary depending on the outcome of asynchronous request handling.Mono<ResponseEntity<Mono<T>>>
or Mono<ResponseEntity<Flux<T>>>
are also possible but less common. They provide the response status and headers asynchronously first and then the response body, also asynchronously at a second point later.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