spring中链式处理

  近来复习了一下spring代码,感觉好的代码还是需要经常看看,从中还是能学到很多东西,虽然我并不看好开源的市场,总觉得开源的东西过于理想,但正因为开源,使我辈等能从中学到一流程序员的设计思路,还是非常感激。

  由于项目的需要,不用java也有一年多的时间,个人还是经常看看java项目的源码,从中吸取其中的思路,在项目中也剽窃了一些。个人觉得思路是相通的,不必在乎编程语言。

  在spring当中,个人当年曾经剽窃了链式处理的思路,用于一个订单审核的流程当中,所以拿出来分享。

  在JdkDynamicAopProxy当中

  invoke方法里面

  。。。。

   List chain = this.advised.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
     this.advised, proxy, method, targetClass);

   。。。。

 

   invocation = new ReflectiveMethodInvocation(
      proxy, target, method, args, targetClass, chain);

    // proceed to the joinpoint through the interceptor chain
    retVal = invocation.proceed();

 

    而 ReflectiveMethodInvocation的proceed()方法

    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
   return invokeJoinpoint();
  }

  Object interceptorOrInterceptionAdvice =
      this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
  if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
 

   InterceptorAndDynamicMethodMatcher dm =
       (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
   if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
    return dm.interceptor.invoke(this);
   }
   else {
        return proceed();
   }
  }
  else {
    return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
  }

  请注意上面红色粗体部分,上面的currentInterceptorIndex为类成员

 

  这一部分和MethodInterceptor一起组成了链式处理,下面是实现MethodInterceptor一个例子

 

public class SpringMethodInterceptor implements MethodInterceptor {

public Object invoke(MethodInvocation invo) throws Throwable { 

   // MethodInvocation invo为上面this传入
   Object[] object = invo.getArguments();
   try{

    System.out.println("信息1");
   
    Object returnObject = invo.proceed();
   
    System.out.println("信息2");
   
    return returnObject;
   }
   catch(Throwable throwable){
   }
   return object;
}

 在上面的 invo.proceed()执行时候,将currentInterceptorIndex加1继续往后执行下去。

 这种链式处理方式使用比较广泛,在java servlet的Filter(过滤器)其实也是使用这种技术。其好处是每个处理比较清晰,并且在某个处理不通过时候,很容易将链结束,不再往后执行。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值