I often see three different response return types: Flux<T>, ResponseEntity<Flux<T>>, and Flux<ResponseEntity<T>> in MVC style controllers using Spring WebFlux. The documentation explains the difference between ResponseEntity<Flux<T>> and Flux<ResponseEntity<T>>. Does Spring automatically wrap Flux<T> as either ResponseEntity<Flux<T>> or Flux<ResponseEntity<T>>? if yes, which one?
Moreover, how to decide which one to return, ResponseEntity<Flux<T>> or Flux<ResponseEntity<T>>? What situation or use case would call for using one over the other?
And, from a webclient's point of view, are there any significant differences when consuming the two types of response?
Spring will automatically wrap that Flux as a ResponseEntity<Flux>. For example if you have a web endpoint as follows
And if you are consuming from a WebClient, you can retrieve your response as either
ResponseEntity<Flux<T>>orFlux<T>. There is no default, but I would think it's good practice to retrieve only Flux unless you explicitly need something from the ResponseEntity. The Spring doc has good examples of this.You actually can consume it as a
Flux<ResponseEntity<T>>, but this would only be applicable for more complex use cases.It really depends on your use case.
Returning
ResponseEntity<Flux<T>>is saying something like,Where
Flux<ResponseEntity<T>>is saying something more likeAgain, I think in most use cases returning just
Flux<T>makes sense (This is equivalent to returningResponseEntity<Flux<T>>)And finally
I think what you're trying to ask is whether you should be using
ResponseEntity<Flux<T>>orMono<ResponseEntity<T>>when consuming from the WebClient. And the spring doc answers this question quite elegantly