我目前正在尝试合并一个 HandlerInterceptorAdapter
但它没有被注册并且将它与其他答案进行比较很难,因为每个人都在使用不同的东西。我知道 WebMvcConfigureAdapter 已被弃用,某些版本控制超出了我对项目范围的控制,请参阅下面的使用规范。
有人可以提供一些关于将拦截器与 RestTemplate(不是 ClientHttpRequestInterceptor)合并的指导。
主要内容:
@SpringBootApplication
@EnableRetry
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder applicationBuilder) {
return applicationBuilder.sources(Application.class);
}
@Bean
private RestTemplate restTemplate(){
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("redacted", 8080));
SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
simpleClientHttpRequestFactory.setProxy(proxy);
simpleClientHttpRequestFactory.setOutputStreaming(false);
RestTemplate template = new RestTemplate();
template.setErrorHandler(new MyResponseErrorHandler());
return template;
}
}
拦截器:com.example.foo.config.request.interceptor
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("INTERCEPTED");
return super.preHandle(request, response, handler);
}
}
拦截器配置:com.example.foo.config.request.interceptor
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Bean
MyInterceptor myInterceptor() {
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
System.out.println("Adding interceptor");
registry.addInterceptor(myInterceptor());
}
}
“添加拦截器”确实被记录下来,所以我知道正在扫描配置。我只是无法记录任何拦截器逻辑。
使用:
- Spring Boot v1.5.15
- Spring 版本:4.3.18.RELEASE
最佳答案
RestTemplate 期望 ClientHttpRequestInterceptor
setInterceptors(List<ClientHttpRequestInterceptor> interceptors)
Set the request interceptors that this accessor should use.
您可以使用 Servlet Filter “拦截”请求/响应,
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response;
implement this with a servlet filter. No Spring involved here at all
但是您必须将 RestTemplate 更改为使用其他框架作为 jersey
Jersey gives a very handy implementation of such as filter called LoggingFilter which can help in logging all kinds of incoming and outgoing traffic.
关于java - Rest模板拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57516825/