What are the differences of Flux<T>, Flux<ResponseEntity<T>>, ResponseEntity<Flux<T>> as return type in Spring WebFlux?
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?
Does Spring automatically wrap Flux as either ResponseEntity<Flux> or Flux<ResponseEntity>? if yes, which one?
Spring will automatically wrap that Flux as a ResponseEntity<Flux>. For example if you have a web endpoint as follows
@GetMapping("/something") public Flux handle() { doSomething() }
And if you are consuming from a WebClient, you can retrieve your response as either ResponseEntity<Flux<T>>
or Flux<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.
Moreover, how to decide which one to return, ResponseEntity<Flux> or Flux<ResponseEntity>? What situation or use case would call for using one over the other?
It really depends on your use case.
Returning ResponseEntity<Flux<T>>
is saying something like,
I am returning a Response of a Collection of type T objects.
Where Flux<ResponseEntity<T>>
is saying something more like
I am returning a Collection of Responses, where the responses have an entity of type T.
Again, I think in most use cases returning just Flux<T>
makes sense (This is equivalent to returning ResponseEntity<Flux<T>>
)
And finally
And, from a webclient's point of view, are there any significant differences when consuming the two types of response?
I think what you're trying to ask is whether you should be using ResponseEntity<Flux<T>>
or Mono<ResponseEntity<T>>
when consuming from the WebClient. And the spring doc answers this question quite elegantly
ResponseEntity<Flux> make the response status and headers known immediately while the body is provided asynchronously at a later point.
Mono<ResponseEntity> provides all three — response status, headers, and body, asynchronously at a later point. This allows the response status and headers to vary depending on the outcome of asynchronous request handling.