what is the difference between ResponseEntity<Mono> and Mono<ResponseEntity> as a return type of a rest controller what is the difference between ResponseEntity<Mono> and Mono<ResponseEntity> as a return type of a rest controller spring spring

what is the difference between ResponseEntity<Mono> and Mono<ResponseEntity> as a return type of a rest controller


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.


https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-responseentity

WebFlux supports using a single value reactive type to produce theResponseEntity asynchronously, and/or single and multi-value reactivetypes for the body.

So the return type on an annotated controller would actually be a Reactive Publisher like Flux or Mono that emits an object representing the data to return.

Example

Flux<AccountDto>

Or also:

Flux<ResponseEntity<AccountDto>>

I think you can even just set a raw DTO type as the return type and Webflux will automagically wrap it in a publisher for you.

Valid Return Types

https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-return-types

Example: https://github.com/oktadeveloper/okta-spring-webflux-react-example/blob/react-app/reactive-web/src/main/java/com/example/demo/ProfileRestController.java

Non-blocking Reactive Paradigm

When doing Reactive Programming you want to every layer to communicate via Flux/Mono. So you would get back a Flux from your ReactiveRepository and the service layer would also return a Flux to the Controller. Basically, in reactive programming everything is a Flux/Mono.

Internals

While SpringMVC and Spring Webflux annotated controllers look similar, they are vastly different internally. For instance, Webflux uses Jetty while SpringMVC uses Tomcat by default. Internally, Webflux is more like a non-blocking event-loop architecture while SpringMVC traditionally leverages a threadpool with 1 thread per request blocking for I/O.

Check out this article for more details on Spring WebFlux