I want to choose a response media type on run time in a method.
For example, the following code:
@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();
}
In this code, the kind of the possible response types are actually 2.
- byte[] (by the normal execution path)
- MyDataException (by the exception execution path)
MyDataException is later handled by an exception handler, and converted to a simple class. It can be converted to a json response.
First, I thought that if I provide 2 response types for produces
option of the @RequestMapping
annotation, the message converter would convert the 2 types according to the actual return object. But it was not the case.
In the spring class org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor
, writeWithMessageConverters()
method just ignores the actual return object type when selecting the response type if the produces
option is present.
How can I let Spring to choose the response type on run time based on the actual return object?