Spring Boot添加Http请求拦截器

发布于 2021-02-02 18:15:50

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

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

关注者
0
被浏览
227
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    由于你使用的是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() {
            ...
        });
      }
    }
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看