• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
你的小铃铛呀
博客园    首页    新随笔    联系   管理    订阅  订阅

拦截器的配置以及执行顺序

在Spring Boot中,拦截器的执行顺序可以通过InterceptorRegistry对象的addInterceptor()方法按照添加的顺序进行配置。

默认情况下,拦截器的执行顺序是按照它们添加到拦截器注册表中的顺序执行的。也就是说,先添加的拦截器会先执行,后添加的拦截器会后执行

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FirstInterceptor())
                .addPathPatterns("/**")
                .order(1); // 设置拦截器的执行顺序为1
        
        registry.addInterceptor(new SecondInterceptor())
                .addPathPatterns("/**")
                .order(2); // 设置拦截器的执行顺序为2
    }
}

在上述例子中,首先注册的是FirstInterceptor拦截器,然后注册的是SecondInterceptor拦截器。因为设置了拦截器的执行顺序,所以FirstInterceptor会先执行,然后才轮到SecondInterceptor执行。

在Spring Boot中,如果前面的拦截器拦截了请求并返回false,后续的拦截器将不会执行。当一个拦截器的preHandle方法返回false时,拦截器链会立即终止,后续的拦截器将不会被执行。

posted @ 2023-06-29 09:28  你的小铃铛呀  阅读(1748)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3