Spring框架学习[创建AOP代理对象并对目标对象切面拦截](三)

2014-11-24 03:05:49 · 作者: · 浏览: 4
} catch (IllegalAccessException ex) { throw new AopInvocationException("Could not access method [" + method + "]", ex); } }

(2).Cglib2AopProxy直接调用目标对象方法:

Cglib2AopProxy是通过methodProxy.invoke来直接调用目标对象的方法,主要源码如下:

[java] view plaincopyprint retVal = methodProxy.invoke(target, args);

methodProxy是CGLIB中MethodProxy类的对象,因为我对CGLIB也不熟悉,这里不做深入了解。

7.AOP拦截器链的调用:

通过上面4和5分别对JdkDynamicAopProxy和Cglib2AopProxy创建AOPProxy代理对象,以及对目标对象的通知器回调我们了解到,当目标对象配置了通知器时,在对目标对象方法调用前首先需要回调通知器链,JdkDynamicAopProxy和Cglib2AopProxy都是通过将目标对象方法、方法参数、和通知器链、代理对象等封装为ReflectiveMethodInvocation类,然后通过ReflectiveMethodInvocation.proceed()方法调用通知器链,proceed方法源码如下:

[java] view plaincopyprint //通用通知器链 public Object proceed() throws Throwable { //如果拦截器链中通知已经调用完毕 if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { //这个方法调用AopUtils.invokeJoinpointUsingReflection方法, //通过反射机制直接调用目标对象方法 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 { //如果不匹配,递归调用proceed()方法,知道拦截器链被全部调用为止 return proceed(); } } else { //如果不是动态匹配方法拦截器,则切入点在构造对象之前进行静态匹配,调用 //拦截器的方法 return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); } }