【发布时间】:2020-10-24 08:13:22
【问题描述】:
我正在尝试让 ClientHttpRequestInterceptor 跟随 Baeldung's Spring RestTemplate Request/Response Logging 工作。问题是 ClientHttpRequestInterceptor 永远不会被调用。
我对 HandlerInterceptor 和 HandlerInterceptorAdapter 拦截器也有类似的问题。问题是我需要添加一个监听器,我发现的 99% 的文章都没有提到。
@Configuration
public class ListenerConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext sc) throws ServletException {
sc.addListener(new RequestContextListener());
}
}
我猜想 Spring 发生了一些变化,默认情况下监听器不在那里。
有人知道 ClientHttpRequestInterceptor 的监听器吗?
拦截器:
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
static Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public ClientHttpResponse intercept(
HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
LOGGER.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
ClientHttpResponse response = ex.execute(req, reqBody);
InputStreamReader isr = new InputStreamReader(
response.getBody(), StandardCharsets.UTF_8);
String body = new BufferedReader(isr).lines()
.collect(Collectors.joining("\n"));
LOGGER.debug("Response body: {}", body);
return response;
}
}
RestClientConfig:
@Configuration
public class RestClientConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors
= restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new LoggingInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
这可能与ClientHttpRequestInterceptor not called in springboot有关。
【问题讨论】:
-
如果您的
RestTemplate工作正常但没有添加拦截器,请将您使用RestTemplate的代码部分放入其中。 -
这是一个简单的 REST 服务。没有
RestTemplate代码,只有一个带有@RestController注释的控制器。在映射方法中带有@RequestBody,应该调用RestTemplate。控制器工作正常。 -
你的控制器中有
@Autowired它吗? -
是的
@Autowired用于服务,控制器调用。该服务构建一个自定义响应模型,控制器返回该模型,Spring 将其转换为响应的 JSON 正文。
标签: java spring spring-boot resttemplate