SpringBoot 过滤器和拦截器( 二 )

配置拦截器:
package com.example.recorddemo.configuration;import com.example.recorddemo.interceptor.MyInterceptor;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.config.annotation.InterceptorRegistration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import javax.annotation.Resource;/** * @author wangchao */@Configurationpublic class InterceptorConfiguration implements WebMvcConfigurer {@ResourceMyInterceptor myInterceptor;/*** 添加拦截器* @param registry*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(myInterceptor).addPathPatterns("/**");}}registry.addInterceptor() 方法会返回当前的 interceptor,因此可直接执行 addPathPatterns() 方法
public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) {InterceptorRegistration registration = new InterceptorRegistration(interceptor);this.registrations.add(registration);return registration;}拦截器的执行顺序类似于栈,按照如下顺序执行:
preHandle-1, preHandle-2, postHandle-2, postHandle-1, afterCompletion-2, afterCompletion-1

推荐阅读