當您使用@ResponseBody
註釋處理程序方法時,Spring使用RequestResponseBodyMethodProcessor
來生成響應主體。爲此,它會在其handleReturnValue
方法,實現爲
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
throws IOException, HttpMediaTypeNotAcceptableException {
mavContainer.setRequestHandled(true);
if (returnValue != null) {
writeWithMessageConverters(returnValue, returnType, webRequest);
}
}
所以,如果返回值是null
,什麼都不會被寫入到身體。
因此,RestTemplate
將嘗試從空的String
反序列化MyDto
。 RestTemplate
使用HttpMessageConvertExtractor
來反序列化響應。該方法extractData
被實現爲
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public T extractData(ClientHttpResponse response) throws IOException {
if (!hasMessageBody(response)) {
return null;
}
MediaType contentType = getContentType(response);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<?> genericMessageConverter = (GenericHttpMessageConverter<?>) messageConverter;
if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Reading [" + this.responseType + "] as \"" +
contentType + "\" using [" + messageConverter + "]");
}
return (T) genericMessageConverter.read(this.responseType, null, response);
}
}
if (this.responseClass != null) {
if (messageConverter.canRead(this.responseClass, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Reading [" + this.responseClass.getName() + "] as \"" +
contentType + "\" using [" + messageConverter + "]");
}
return (T) messageConverter.read((Class) this.responseClass, response);
}
}
}
throw new RestClientException(
"Could not extract response: no suitable HttpMessageConverter found for response type [" +
this.responseType + "] and content type [" + contentType + "]");
}
換句話說,如果沒有體,它返回null
。
所以這裏
MyDto obj = restTemplate.getForObject(url, MyDto.class);
您MyDto
對象將是null
。