I have a spring boot 2 application, in which I have to log every request and response made by using Rest Template. For instance, if I have to call another service, this needs to get logged in my db. For this, I made the following changes in the Rest Template Config
@Configuration
@Getter
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate template = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = template.getInterceptors();
if (CollectionUtils.isEmpty(interceptors))
interceptors = new ArrayList<>();
interceptors.add(new RequestResponseLoggingInterceptor());
template.setInterceptors(interceptors);
return template;
}
}
And the interceptor code is
public class RequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
ResponseLoggingRepository loggingRepository = BeanUtils.getBean(ResponseLoggingRepository.class);
ResponseLoggingEntity entity = ResponseLoggingEntity.build(request, body);
loggingRepository.save(entity);
ClientHttpResponse response = execution.execute(request, body);
ResponseLoggingEntity.build(response, entity);
loggingRepository.save(entity);
return response;
}
}
The code works perfectly fine and I'm successfully able to log the response in the db. The issue is when I use the rest template exchange method, I always receive the null object.
ResponseObject response = restTemplate.postForObject(url, requestObject,
ResponseObject.class);
This response object is always null whenever I test. However, if I remove the interceptor from the rest template, I get proper response in my object.
I further debugged and checked for the internal converters at the time of rest template config initialization, and I'm able to see the MappingJackson2HttpMessageConverter which as per my understanding, is the one which converts the response from JSON to the required object. I think some additional configuration is needed so that the response object obtains the required mapping and I have no clue as to what is missing in this case? Could anyone please help? Thanks.