Spring 拦截器Interception 和 AOP 做全局处理的使用方式与使用场景分析

简介:

Interceptor和aop:依赖spring框架,基于java反射和动态代理实现,只能拦截controller的请求,可以获取ioc容器中的bean
拦截顺序:Interception > AOP > 具体执行的方法 > AOP > @ControllerAdvice > Interception

Interceptor

Interceptor是依赖于Spring框架,是aop的一种表现,基于Java的动态代理实现的。

使用步骤:

  1. 声明拦截器的类:通过实现 HandlerInterceptor接口,实现preHandle、postHandle和afterCompletion方法。
  2. 通过配置类配置拦截器:通过实现WebMvcConfigurer接口,实现addInterceptors方法。

举个栗子,上代码:
1.声明拦截器:MyInterceptor.java

public class MyInterceptor implements HandlerInterceptor{
   

    /**
     * 预处理回调方法,实现处理器的预处理(如检查登陆),第三个参数为响应的处理器
     * 返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        System.out.println("====拦截到了方法:"+methodName+",preHandle====");
        return true;
    }

    /**
     * 后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Kotlin 中,自定义拦截器Interceptor)通常用于实现 AOP(面向切面编程)的概念,它可以在不修改原始代码的情况下,动态地加入额外的行为或修改方法的执行流程。Kotlin 提供了 `kotlinx.coroutines` 库中的 `CoroutineScope` 和 `CoroutineContext` 接口,以及 `kotlinx.android.synthetic` 在 Android 开发中对 Activity、Fragment 等的扩展,这些地方都可以使用拦截器。 在 `CoroutineScope` 上,你可以使用 `install` 方法来添加一个拦截器,如 `startCoroutineWithIntercept`: ```kotlin val scope = CoroutineScope(Dispatchers.Main) // 获取主线程的CoroutineScope scope.install(MyInterceptor()) // 安装自定义拦截器 ``` `MyInterceptor` 类可能会像这样定义: ```kotlin class MyInterceptor : CoroutineContextElement { override fun install(context: CoroutineContext): CoroutineContext { return context + this // 将拦截器添加到上下文中 } override suspend fun intercept(context: CoroutineContext, block: suspend () -> Unit): Any? { val startTime = System.currentTimeMillis() // 记录开始时间 try { return block() // 执行原始的协程块 } finally { val endTime = System.currentTimeMillis() println("Interception finished in $endTime - $startTime ms") // 输出拦截后信息 } } } ``` 在 Android 中,自定义拦截器可能用来记录日志、处理错误或者实现特定的功能,比如在 Fragment 中: ```kotlin val fragment = requireFragmentManager().findFragmentById(R.id.my_fragment) as MyFragment fragment.coroutineContext = fragment.coroutineContext + MyFragmentInterceptor() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值