javaspringspring-mvcspring-restspring-web

Should OutputStream be closed explicit in StreamingResponseBody?


I'm streaming a big external resource using StreamingResponseBody in a spring @RestController.

Question: should the OutputStream of the response body be closed explicit here?

@GetMapping("/{filename}")
public ResponseEntity<StreamingResponseBody> getFile(@PathVariable String filename) {
            StreamingResponseBody responseBody = outputStream -> {
                resolveExternally(outputStream, response, filename);

                //TODO should the stream be closed explicit here?
                //outputStream.close();
            };

            return ResponseEntity.ok(responseBody);
}

Solution

  • It will be closed by the container. Check StreamingResponseBodyReturnValueHandler.

    OutputStream wraps a native HttpServletResponse.

    HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
    Assert.state(response != null, "No HttpServletResponse");
    ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
    

    If you follow it down you will get to CoyoteAdapter which is calling finishResponse() and closing OutputBuffer.