我正在使用Spring Boot 2.0 Spring Webflux构建一个利用zero-copy NIO功能的文件控制器。我也想发送自定义响应头(用于响应缓存等)
代码如下:
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping(value = "/{fileName:.+}")
public Mono<ServerResponse> getFile(@PathVariable("fileName") String fileName) {
Resource body = new ClassPathResource(fileName);
return ServerResponse.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, String.format("inline; filename=\"%s\"", fileName))
.contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromResource(body));
}
}
但是当我从浏览器执行请求时,在服务器日志中出现以下错误:
2018-07-23 12:07:53.928 ERROR 9772 --- [ctor-http-nio-3] o.s.w.s.adapter.HttpWebHandlerAdapter : Unhandled failure: Type definition error: [simple type, class org.springframework.web.reactive.function.server.DefaultServerResponseBuilder$BodyInserterResponse]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.web.reactive.function.server.DefaultServerResponseBuilder$BodyInserterResponse and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS), response already set (status=null)
2018-07-23 12:07:53.928 WARN 9772 --- [ctor-http-nio-3] o.s.h.s.r.ReactorHttpHandlerAdapter : Handling completed with error: Type definition error: [simple type, class org.springframework.web.reactive.function.server.DefaultServerResponseBuilder$BodyInserterResponse]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.web.reactive.function.server.DefaultServerResponseBuilder$BodyInserterResponse and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
我不知道这里出了什么问题。如果我从控制器方法返回Mono<Resource>
,那么一切正常,但是我失去了提供客户响应标题的灵活性。
对此有任何帮助。
答案 0 :(得分:2)
ServerResponse
仅应与Spring WebFlux功能一起使用-对于带有注释模型的此用例,ResponseEntity
是正确的选择。
因为WebFlux注释模型无法识别ServerResponse
类型,所以它假定应该对它进行序列化(在这里,使用Jackson)。