Skip to content

Add body(Object) method to ServerResponse.BodyBuilder [SPR-15461] #20021

Closed
@spring-projects-issues

Description

@spring-projects-issues

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.

  1. Give the method a different name, such as bodyFromObject. If we go this route, we should be consistent and also rename the existing Publisher-based body method to bodyFromPublisher. As such, it has serious consequences for the brevity and UX of the API.
  2. Perform a runtime-check to see whether the Object passed to body is a Publisher, and throw an exception if so, warning the user of the error of their ways.
  3. 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:

Referenced from: commits 30f61e0

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions