It could be achieved with a ResponseBodyAdvice
:
Allows customizing the response after the execution of an @ResponseBody
or a ResponseEntity
controller method but before the body is written with an HttpMessageConverter
.
Implementations may be registered directly with RequestMappingHandlerAdapter
and ExceptionHandlerExceptionResolver
or more likely annotated with @ControllerAdvice
in which case they will be auto-detected by both.
So you could have something like:
@ControllerAdvice
public class MyResponseBodyAdvisor implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class);
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
MyResponseWrapper wrapper = new MyResponseWrapper();
wrapper.setData(body);
return wrapper;
}
}
Where MyResponseWrapper
is your class used to wrap the response payload.