1. 程式人生 > >spring中aop原始碼分析(五)

spring中aop原始碼分析(五)

spring中原始碼分析(五)

我們接著JdkDynamicAopProxy下面的invoke方法下面 進行分析

   // We need to create a method invocation...
   invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
   // Proceed to the joinpoint through the interceptor chain.
   retVal = invocation.proceed();

上面核心的為兩句一個是為了構造物件一個是執行上面方法:

這裡發現它實現了ProxyMethodInvocation介面

我們進入到構造方法中,裡面只是簡單的進行賦值操作

protected ReflectiveMethodInvocation(
      Object proxy, @Nullable Object target, Method method, @Nullable Object[] arguments,
      @Nullable Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {

   this.proxy = proxy;
   this.target = target;
   this.targetClass = targetClass;
   this.method = BridgeMethodResolver.findBridgedMethod(method);
   this.arguments = AopProxyUtils.adaptArgumentsIfNecessary(method, arguments);
   this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
}

如何我們看它的procced方法

public Object proceed() throws Throwable {
   // 如果當前攔截器索引為最後一個直接執行目標方法
   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 {
         // Dynamic matching failed.
         // Skip this interceptor and invoke the next in the chain.
         return proceed();
      }
   } else {
      //這裡就呼叫攔截器上面的方法 這裡攔截器可能為ThrowsAdviceInterceptor
      return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
   }
}