小编典典

Spring Boot添加Http请求拦截器

spring

在Spring Boot应用程序中添加HttpRequest拦截器的正确方法是什么?我想做的是记录每个HTTP请求的请求和响应。

我发现了一些有关如何对较早版本的spring进行相同操作的Web示例,但这些示例与applicationcontext.xml一起使用。请帮忙。


阅读 785

收藏
2020-04-12

共1个答案

小编典典

由于你使用的是Spring Boot,因此我假设你希望在可能的情况下依靠Spring的自动配置。要添加其他自定义配置(例如你的拦截器),只需提供一个配置或WebMvcConfigurerAdapter

这是一个配置类的例子:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired 
  HandlerInterceptor yourInjectedInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(...)
    ...
    registry.addInterceptor(getYourInterceptor()); 
    registry.addInterceptor(yourInjectedInterceptor);
    // next two should be avoid -- tightly coupled and not very testable
    registry.addInterceptor(new YourInterceptor());
    registry.addInterceptor(new HandlerInterceptor() {
        ...
    });
  }
}
2020-04-12