zoukankan      html  css  js  c++  java
  • Spring源码解析-Advice中的Adapter模式

    在spring中与通知相关的类有:

           以Advice结尾的通知接口

         MethodBeforeAdvice    AfterReturningAdvice   ThrowsAdvice

          以Interceptor结尾的拦截器

              MethodBeforeAdviceInterceptor   AfterReturningAdviceInterceptor   ThrowsAdviceInterceptor

         以Adapter结尾的适配器

               MethodBeforeAdviceAdapter   AfterReturningAdviceAdapter  ThrowsAdviceAdapter

         先了解一下Adapter模式

         

         而这三者间的关系以MethodBefore为例:

         

    下面以MethodBefore为例,看一下源码。

    先看一下AdvisorAdapter接口

    public interface AdvisorAdapter {
    
        boolean supportsAdvice(Advice advice);
    
        
        MethodInterceptor getInterceptor(Advisor advisor);
    
    }

    MethodBeforeAdviceAdapter类

    class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
    
        @Override
        public boolean supportsAdvice(Advice advice) {
            return (advice instanceof MethodBeforeAdvice);
        }
    
        @Override
        public MethodInterceptor getInterceptor(Advisor advisor) {
            MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
            return new MethodBeforeAdviceInterceptor(advice);
        }
    
    }

    而MethodBeforeAdviceInterceptor是具体的实现。

    例外在看一下MethodBeforeAdviceInterceptor类

    public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
    
        private MethodBeforeAdvice advice;
    
    
        /**
         * Create a new MethodBeforeAdviceInterceptor for the given advice.
         * @param advice the MethodBeforeAdvice to wrap
         */
        public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
            Assert.notNull(advice, "Advice must not be null");
            this.advice = advice;
        }
    
        @Override
        public Object invoke(MethodInvocation mi) throws Throwable {
            this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
            return mi.proceed();
        }
    
    }

    实现了MethodIntercepter接口,在调用invoke进行拦截的时候,是先调用before方法里面,然后在调用具体的方法实现。

           

  • 相关阅读:
    那些值得收藏的神奇的网站,使用RSS阅读器订阅喜欢的网站 --授人以鱼不如授人以渔
    截图与屏幕录像利器:FastStone Capture
    Java基础数据类型
    刚刚开通了博客园,欢迎来踩
    ETL 各种小问题笔记
    SpringBoot 项目打包部署Resin遇到的问题
    跟据html页面生成图片方便打印分享
    微信将用户信息转为一张图片(将html转为图片)
    Js处理本地视频和第三方视频播放的问题
    反射+特性实现 类和XML文档的序列化反序列化
  • 原文地址:https://www.cnblogs.com/lzeffort/p/7841629.html
Copyright © 2011-2022 走看看