【发布时间】:2015-07-25 13:10:19
【问题描述】:
我想在方法的运行时选择响应媒体类型。
例如下面的代码:
@RequestMapping(value = "/getRecord",
produces = {"application/octet-stream", "application/json;charset=UTF-8" })
public byte[] getData(
@RequestParam(value="id", required=true) Integer id)
throws IOException
{
if (id == 1)
return createByteArray();
throw new MyDataException();
}
在这段代码中,可能的响应类型实际上是 2。
- byte[](通过正常执行路径)
- MyDataException(通过异常执行路径)
MyDataException 稍后由异常处理程序处理,并转换为简单类。它可以转换为 json 响应。
首先,我认为如果我为@RequestMapping注解的produces选项提供2种响应类型,消息转换器将根据实际返回对象转换2种类型。但事实并非如此。
在spring类org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor中,如果produces选项存在,writeWithMessageConverters()方法在选择响应类型时只是忽略实际返回对象类型。
如何让Spring根据实际返回对象在运行时选择响应类型?
【问题讨论】:
标签: spring spring-mvc spring-boot