温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

拦截器生命周期是什么

发布时间:2026-08-30 06:52:47 来源:亿速云 阅读:88 作者:小樊 栏目:编程语言

拦截器(Interceptor)生命周期 取决于具体技术栈,不同框架中含义不同。下面区分几种最常见的场景说明:


一、Spring MVC 拦截器(HandlerInterceptor)生命周期

Spring MVC 的拦截器不是单例随容器启动就结束,而是围绕一次 HTTP 请求存在。

1️⃣ 创建阶段(容器启动)

  • 拦截器实例在 Spring 容器启动时创建
  • 默认是 单例
  • 只会创建一次
public class MyInterceptor implements HandlerInterceptor {
    public MyInterceptor() {
        System.out.println("拦截器被创建");
    }
}

✅ 生命周期起点:Spring 容器启动


2️⃣ 请求处理阶段(一次请求)

一个 HTTP 请求会依次触发拦截器的方法:

preHandle → Controller → postHandle → afterCompletion

方法执行顺序

方法 执行时机 是否可中断
preHandle Controller 执行前 ✅ 返回 false 可中断
postHandle Controller 执行后,视图渲染前
afterCompletion 整个请求完成后(包括视图渲染)
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    System.out.println("preHandle");
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) {
    System.out.println("postHandle");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    System.out.println("afterCompletion");
}

3️⃣ 请求结束

  • 单次请求结束
  • 拦截器实例 不会被销毁
  • 等待下一个请求复用(因为是单例)

4️⃣ 容器销毁

  • Spring 容器关闭时
  • 拦截器实例随容器销毁

✅ Spring MVC 拦截器生命周期总结

容器启动 → 创建拦截器(单例)
    ↓
每次请求 → preHandle → Controller → postHandle → afterCompletion
    ↓
容器关闭 → 销毁拦截器

二、MyBatis 拦截器(Interceptor)生命周期

MyBatis 拦截器生命周期与 SqlSessionFactory 绑定

特点

  • MyBatis 初始化时创建
  • 作用于 SQL 执行过程
  • 通常用于:
    • 分页
    • SQL 重写
    • 性能监控
@Intercepts({@Signature(type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class})})
public class MyBatisInterceptor implements Interceptor {
}

生命周期

MyBatis 初始化 → 创建拦截器
    ↓
每次 SQL 执行 → 拦截器生效
    ↓
应用关闭 → 销毁

三、Struts2 拦截器生命周期(了解)

  • 每次请求创建新的 ActionContext
  • 拦截器在请求中创建
  • 请求结束即销毁

四、OKHttp / Retrofit 拦截器(Android)

  • 应用生命周期内存在
  • 用于:
    • 日志
    • 请求头添加
    • 重试

五、总结对比

框架 生命周期范围 是否单例
Spring MVC 容器级
MyBatis SqlSessionFactory 级
Struts2 请求级
OKHttp 应用级

如果你指的是 某一个具体框架(如 Spring Boot / MyBatis / Vue / Axios),告诉我,我可以精确到源码级别解释。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI