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.