Plenty of question in SO but almost no working solution.
Just a simple implementation of ResponseAdvice with @ControllerAdvice
Controller
@RestController
@ReqeustMapping("/test")
class TestController{
@RequestMapping( method=GET )
public String test(){ return "Test"; }
}
Advice
@RestControllerAdvice
public class ResponseDecorator implements ResponseBodyAdvice<String> {
@Autowired
ObjectMapper mapper;
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getParameterType().equals(String.class);
}
@Override
public String beforeBodyWrite(String body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
System.out.println ( "Just print this when before sending ");
return body;
}
}
The beforeBodyWrite does not trigger at all. The app is fully annotation driven. And both advice and controller are in same package. What am I missing!
Ok. Silly mistake.The issue here is the supports methods
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getParameterType().equals(String.class);
}
making this method return TRUE has fixed the issue.
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
The supports method should return true. So adjust your logic based on your requirement.