问题
I have a Spring boot REST API app. I have a use-case to add some common parameters to all API responses such as time
and clientId
. To achieve this, I am using a ResponseBodyAdvice
to manipulate the output of controllers. However, if a controller returns null
, the ResponseBodyAdvice
doesn't get called. I have verified this by adding logs and breakpoints.
My question is how do i overcome this behavior? Basically for cases when a controller returns null
such a when no data exists, I still want my API output to contain the common fields.
This is my expected output for API GET /users/{userId}
when there is no user for the given id.
{
"time": "2018-11-10 23:00:00",
"clientId": "MyClient",
"data": null
}
However as my ResponseBodyAdvice is not executing, I am getting no output only 200
with other headers.
Here is the code of my ResponseBodyAdvice
@ControllerAdvice("com.tl.core.controller")
public class TLResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println("::RBA:: supports");
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
System.out.println("::RBA:: beforebodywrite1 " + body);
if(returnType.getMethod().getName().equalsIgnoreCase("handleControllerException")) {
return body;
}
System.out.println("::RBA:: beforebodywrite2");
final RestResponse<Object> output = new RestResponse<>(HttpStatus.OK.value());
output.setData(body);
// set common fields here.
...
return output;
}
@ExceptionHandler(Exception.class)
@ResponseBody
public TLResponseEntity<Object> handleControllerException(HttpServletRequest request, Throwable ex) {
final RestResponse<Object> output = new RestResponse<>(HttpStatus.INTERNAL_SERVER_ERROR.value());
// set common fields here
...
final TLResponseEntity<Object> finaloutput = new TLResponseEntity<>(output);
return finaloutput;
}
}
回答1:
You need to return as follows from your controller in order to execute the ResponseBodyAdvice in case of NULL response.
new ResponseEntity<>(null, HttpStatus.OK);
Then once your ResponseBodyAdvice is executed you can restructure your response.
Basically your controller should not just return NULL but the ResponseEntity with NULL data would force required behaviour for your case.
来源:https://stackoverflow.com/questions/54055490/spring-mvc-responsebodyadvice-doesnt-get-called-for-null-response-from-control