从 REST 控制器返回的 InputStreamResource 中未释放的 InputStream

ASt*_*ten 5 java file-io spring-mvc fortify

我的 REST 控制器中有这样一个方法,返回文件数据:

@RequestMapping(
        value  = "by-id/{attachmentId}",
        method = RequestMethod.GET
)
public ResponseEntity<InputStreamResource> attachmentById(
        @PathVariable("attachmentId") String attachmentId) {
    GridFSDBFile file = service.getAttachment(attachmentId);

...... some unrelated code here, setting headers, etc .....

    return new ResponseEntity<InputStreamResource>(
                new InputStreamResource(file.getInputStream()), respHeaders, HttpStatus.OK);

}
Run Code Online (Sandbox Code Playgroud)

这工作得很好,但是根据 Fortify 的报告,我将释放 InputStream,显然是在file.getInputStream(). 也许,我必须使用 try-with-resources,因为 InputStream 是可自动关闭的,或者file.getInputStream().close()finally块中调用。但似乎我不能这样做,因为我完全不知道 的构造函数InputStreamResource及其方法的实现,也不知道该输入流是否仍在返回的 ResponseEntity 中使用。

我是什么做的?

msh*_*tov 3

我认为您已经能够找到问题的答案。并且,可能,这对 Fortify 来说是一个问题,因为 Spring 关闭了流 - 请参阅“调查” -如何在 Spring MVC 中处理 IO 流