Issue
I want to access HTTP Request and response payload in one place of code. I try to implementing RequestBodyAdvice and ResponseBodyAdvice in separated classes and it worked fine, but in two separated places of code. Then I try to implement these two in one class but only methods of either RequestBodyAdvice or ResponseBodyAdvice invoked. for example in below code only beforeBodyRead and afterBodyRead(these are owned by RequestBodyAdvice) invoked;and it is strange for me that these two invoked two times for every request!(at the time that I implement these interfaces in separated classes every method invoked only once):
@ControllerAdvice
public class CustomResponseBodyAdviceAdapter implements RequestBodyAdvice, ResponseBodyAdvice<Object>{
public CustomResponseBodyAdviceAdapter() {
}
@Override
public boolean supports(MethodParameter methodParameter,
Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o,
MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
return o;
}
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
return httpInputMessage;
}
@Override
public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return o;
}
@Override
public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return o;
}
}
I want to implement these two interfaces in one class in the way that all methods invoke correctly.
Update: Spring boot version is 2.0.1.RELEASE
Solution
It's already implemented under the hood of Spring.
The class has private-package access but you can copy it and implement both supports()
methods according to your requirements.
Updated
The PoC you can find here
Answered By - Andrei Kovrov
Answer Checked By - Mildred Charles (JavaFixing Admin)