• 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方法里面,然后在调用具体的方法实现。

           

  • 相关阅读:
    计算tableview的高度
    UIcollectionview与tableview的区别
    ios 屏幕适配
    避免表单多次提交
    Action权限验证
    正则小记
    在OnActionExecuting中阻止后面Action的执行
    批量上传图片uplodify插件
    表单多次提交
    windows 下安装 rabbitmq报init terminating in do_boot错误
  • 原文地址:https://www.cnblogs.com/lzeffort/p/7841629.html
Copyright © 2020-2023  润新知