spring boot添加http请求拦截器 [英] spring boot adding http request interceptors

查看:326
本文介绍了spring boot添加http请求拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the right way to add HttpRequest interceptors in spring boot application? What I want to do is log requests and responses for every http request.

Spring启动文档根本不涉及这个主题。 ( http://docs.spring.io/spring-boot/docs/current/reference/ htmlsingle /

Spring boot documentation does not cover this topic at all. (http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/)

我发现了一些关于如何对旧版本spring执行相同操作的Web示例,但这些示例与applicationcontext.xml一起使用。请帮助。

I found some web samples on how to do the same with older versions of spring, but those work with applicationcontext.xml. Please help.

推荐答案

由于您使用的是Spring Boot,我认为您更愿意尽可能依赖Spring的自动配置。要添加其他自定义配置(如拦截器),只需提供 WebMvcConfigurerAdapter 的配置或bean。

Since you're using Spring Boot, I assume you'd prefer to rely on Spring's auto configuration where possible. To add additional custom configuration like your interceptors, just provide a configuration or bean of 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() {
        ...
    });
  }
}

注意请勿注释如果你想保留 mvc的Spring Boots自动配置

NOTE do not annotate this with @EnableWebMvc, if you want to keep Spring Boots auto configuration for mvc.

这篇关于spring boot添加http请求拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆