spring - 为什么 spring 中的 AsyncRestTemplate 没有像 RestTemplate 这样的拦截器?

标签 spring spring-web

我有一种情况需要拦截请求,并且需要在该请求中设置授权 header 。 所以我得到了解决方案,我可以使用拦截器来设置该 header ,但是当我检查 AsyncRestTemplate 时,它没有像 RestTemplate 这样的属性。

是否有任何特定原因不包括该属性?

最佳答案

AsyncRestTemplate 扩展了 InterceptingAsyncHttpAccessor 抽象类,它公开了方法 setInterceptors。所以你当然可以设置拦截器,就像你对非异步 RestTemplate 所做的那样。请注意,您的拦截器需要改为实现 AsyncClientHttpRequestInterceptor:

public class AsyncFooBarInterceptor implements AsyncClientHttpRequestInterceptor {

    @Override
    public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException {
        return null; // do your thing instead
    }
}

然后使用它:

AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
asyncRestTemplate.setInterceptors(Collections.singletonList(new AsyncFooBarInterceptor()));

关于spring - 为什么 spring 中的 AsyncRestTemplate 没有像 RestTemplate 这样的拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653418/

相关文章:

spring - hibernate - 如果父级设置了级联,则无法删除子级

java - 扩展通用 Controller 时 Spring mvc 错误

Java RestTemplate 卡在 204 状态代码响应上

java - 使用Spring进行数据库和网页集成

spring - Spring Data MongoDb-如何使用仅返回有效文档的“findAll”方法

java - Spring Autowiring

Spring Boot 使用自动配置创建多个(正常运行的)webmvc 应用程序

java - Spring 的 @RequestParam 与 Enum

java - Spring 网络 MVC : no request body possible for HTTP DELETE anymore

spring - 更新到最新版本后替换@EnableSwagger2