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(过滤器)其实也是使用这种技术。其好处是每个处理比较清晰,并且在某个处理不通过时候,很容易将链结束,不再往后执行。