Description
Arjen Poutsma opened SPR-15461 and commented
We should add a ServerResponse.BodyBuilder.body(Object)
method, to make it easier for users to set the response body to a non-Publisher type. Currently, this task can be accomplished via body(BodyInserters.fromObject(Object))
, but because this method requires a static import of BodyInserters
, the discoverability of it is not as high as body(Publisher, Class))
. As such, users will go this route:
return ServerResponse.ok().body(Mono.just("Hello World"), String.class);
instead of the more elegant:
return ServerResponse.ok().body(fromObject("Hello World"));
However, adding the method has a serious consequence: there is the potential for accidental method overloading between a the new Object
method and the existing Publisher
body
method. As a result, users will accidentally write a response with the publisher itself, rather than its contents:
Flux<String> flux = ...
return ServerResponse.ok().body(flux); // Whoops, should have been body(flux, String.class);
Of course, we cannot automatically call the correct method, because of the lacking Class
argument. There are, however, a couple of other ways we can resolve this.
- Give the method a different name, such as
bodyFromObject
. If we go this route, we should be consistent and also rename the existingPublisher
-basedbody
method tobodyFromPublisher
. As such, it has serious consequences for the brevity and UX of the API. - Perform a runtime-check to see whether the
Object
passed to body is aPublisher
, and throw an exception if so, warning the user of the error of their ways. - Do not add the method. Since this a Reactive web framework, the case can be made that returning non-reactive types as a response is not a main design goal. Returning a String makes for a great demo, but might not be as necessary for real-life reactive scenarios.
Issue Links:
- ServerResponse.BodyBuilder.body(Object) shadows body(Publisher) in Kotlin ServerResponseExtensions [SPR-15467] #20027 ServerResponse.BodyBuilder.body(Object) shadows body(Publisher) in Kotlin ServerResponseExtensions
Referenced from: commits 30f61e0