Согласно вашему коду, вы зарегистрировали пустой список перехватчиков в RestTemplate.Попробуйте изменить свой код следующим образом:
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// check if restTeamplate doesn't already have other interceptors
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new RestTemplateHeaderModifierInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
Более подробная информация здесь .
Этот перехватчик будет обслуживать исходящие запросы.
Для запросов доход вы должны унаследовать ваш перехватчик от HandlerInterceptorAdapter
:
public class MyIncomeRequestInterceptor extends HandlerInterceptorAdapter {
//...
}
, а затем зарегистрировать его с помощью WebMvcConfigurer
следующим образом, например:
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyIncomeRequestInterceptor());
}
};
}
Более подробная информация здесь .
В обоих случаях нет необходимости делать бобы из ваших перехватчиков (вы можете удалить аннотацию @Component
).
ОБНОВЛЕНИЕ
Рабочий пример:
@Slf4j
@RestController
@ControllerAdvice
@SpringBootApplication
public class Application implements WebMvcConfigurer, ResponseBodyAdvice<Object> {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping("/hello")
public ResponseEntity<?> hello() {
return ResponseEntity.ok(Map.of("message", "hello"));
}
@EventListener
public void onReady(final ApplicationReadyEvent e) {
Map result = restTemplate().getForObject("http://localhost:8080/hello", Map.class);
if (result != null) {
log.info("[i] Request result: '{}'", result.get("message"));
}
}
@Bean
public RestTemplate restTemplate() {
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);
var interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) interceptors = new ArrayList<>();
interceptors.add(new OutgoingInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new IncomingInterceptor());
}
@Override
public boolean supports(final MethodParameter returnType, final Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(final Object body, final MethodParameter returnType, final MediaType selectedContentType, final Class<? extends HttpMessageConverter<?>> selectedConverterType, final ServerHttpRequest request, final ServerHttpResponse response) {
log.info("[i] ResponseBodyAdvice: response body {}", body);
return body;
}
class OutgoingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] bytes, final ClientHttpRequestExecution execution) throws IOException {
log.info("[i] Outgoing interceptor: requested URL is '{}'", request.getURI());
ClientHttpResponse response = execution.execute(request, bytes);
String body = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
log.info("[i] Outgoing interceptor: response body is '{}'", body);
return response;
}
}
class IncomingInterceptor implements HandlerInterceptor {
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView mw) throws Exception {
log.info("[i] Incoming interceptor: requested URL is '{}'", request.getRequestURL().toString());
}
}
}
Для записи тела ответов каждого метода контроллеров IMO лучше использовать реализацию ResponseBodyAdvice
с@ControllerAdvice
аннотация (см. Выше в коде).
Результат:
2019-01-16 14:05:07.260 : [i] Outgoing interceptor: requested URL is 'http://localhost:8080/hello'
2019-01-16 14:05:07.366 : [i] ResponseBodyAdvice: response body {message=hello}
2019-01-16 14:05:07.383 : [i] Incoming interceptor: requested URL is 'http://localhost:8080/hello'
2019-01-16 14:05:07.387 : [i] Outgoing interceptor: response body is '{"message":"hello"}'
2019-01-16 14:05:07.402 : [i] Request result: 'hello'
Репо: sb-web-interceptors-demo