Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-15461

Add body(Object) method to ServerResponse.BodyBuilder

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Minor
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 5.0 RC1
    • Component/s: Reactive, Web
    • Labels:
      None
    • Last commented by a User:
      false

      Description

      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.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                arjen.poutsma Arjen Poutsma
                Reporter:
                arjen.poutsma Arjen Poutsma
                Last updater:
                St├ęphane Nicoll
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved:
                  Days since last comment:
                  1 year, 6 days ago