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

推薦閱讀