Spring框架学习[AOP通知以及编程式AOP ](二)

2014-11-24 03:05:50 · 作者: · 浏览: 1
配置的通知器:

Spring通过调用ReflectiveMethodInvocation类来处理AOP配置的通知,CglibMethodInvocation继承ReflectiveMethodInvocation,因此JDK和CGLIB方式都是通过调用ReflectiveMethodInvocation的proceed()方法来处理通知的,处理通知的源码如下:

[java] view plaincopyprint //处理AOP配置的通知 public Object proceed() throws Throwable { //如果拦截器链中通知已经调用完毕 if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { //这个方法调用AopUtils.invokeJoinpointUsingReflection方法, //通过反射机制直接调用目标对象方法 return invokeJoinpoint(); } //获取AOP配置的通知,在ReflectiveMethodInvocation初始化构方法中将获 //取到的AOP通知赋值给interceptorsAndDynamicMethodMatchers变量 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); } }

2.AOP代理创建辅助类AdvisedSupport获取通知:

在1中我们看到,获取AOP通知的的方法如下:

[java] view plaincopyprint Listchain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

该方法会通过AOP代理创建辅助类AdvisedSupport获取AOP配置的通知,获取通知的过程如下:

(1).AdvisedSupport获取给定方法的通知:

[java] view plaincopyprint //获取通知 public ListgetInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) { //使用cache缓存 MethodCacheKey cacheKey = new MethodCacheKey(method); //首先从缓存中获取 Listcached = this.methodCache.get(cacheKey); //如果缓存中没有,即第一次调用 if (cached == null) { //从通知器链容器中获取通知,这里使用的DefaultAdvisorChainFactory cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice( this, method, targetClass)