Spring Webflux: Controller return Mono<ResponseEntity<MyPojo>> vs Mono<MyPojo>

Viewed 2042

Small question regarding some return type I have seen for Spring Webflux please.

In many examples, like online tutorials, the rest web controller of a Spring Webflux project will return a Mono of MyPojo Mono<MyPojo> something like

    public Mono<MyPojo> monoPojo(String parameter) {
        return WebClient.create("http://...").get().retrieve().bodyToMono(MyPojo.class)
                .map(oneMyPojo -> unregisterRepository.insert(oneMyPojo))
                ;
    }

But I am also bumping into projects where it returns the response entity, the Mono of response entity of MyPojo Mono<ResponseEntity<MyPojo>>:

    public Mono<ResponseEntity<MyPojo>> monoResponseEntityPojo(String parameter) {
        return WebClient.create("http://...").get().retrieve().bodyToMono(MyPojo.class)
                .map(oneMyPojo -> unregisterRepository.insert(oneMyPojo))
                .map(ResponseEntity::ok)
                ;
    }

I am having a hard time understanding the use of Mono<ResponseEntity>. May I ask what kind of benefits this Mono<ResponseEntity> can bring over Mono please?

Thank you

1 Answers

Lets clear some things up

A ResponseEntity<T> is from the org.springframework.httppackage while a ServerResponse is from the org.springframework.web.reactive.function.server package.

This should as a start should give you a hint of when to use what, and where.

But in short, you can use webflux in 2 ways, either by using old fashioned @RestController annotations, with annotated functions for each path. This a sort of "backwards compatibility mode" between regular servlet spring web, and webflux async event driven programming.

ResponseEntities are returned from old spring-web while if you instead opt in to use functional enpoints that exist in webflux, you need to return ServerResponses.

If you look in the code for the classes you will se that they work some parts the same, but other parts differently, especially how they store the body and serialize the bodies.

Handler functions and Filter functions in webflux only work with ServerResponses.

Now to your question, returning Mono<ResponseEntity<T> or Mono<T>.

Well it all comes down to how lazy you are.

If you return a Mono<T> the framework will try to figure out what type of content you have in the Mono, and then create a ResponseEntity accordingly. So if you are serializing it into json, it will set the content-type for you, and set the status usually to 200 OK

While if you wish, you can build your ResponseEntity completely custom, and return any status code, with any body, and any headers etc. etc.

So what it all comes down to is how lazy are you, how much do you want the framework to do for you, and how much to do you want to be explicit, and and type out everything by yourself, or customize.

Me, im lazy, i just return something that works.

Related