Spring Boot 添加 Http 请求拦截器 [英] Spring Boot Adding Http Request Interceptors

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

问题描述

在 Spring Boot 应用程序中添加 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 boot 文档根本没有涉及这个主题.(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.

这是一个配置类的例子:

Here's an example of a config class:

@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 自动配置.

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

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