粗浅分析注解spring AOP源码--------(二)

9 篇文章 0 订阅
5 篇文章 0 订阅

AnnotationAwareAspectJAutoProxyCreator执行时机

AnnotationAwareAspectJAutoProxyCreatorInstantiationAwareBeanPostProcessor的实现类,实现了 postProcessBeforeInstantiation()postProcessAfterInstantiation()两个方法,这两个方法的执行时机就是在分别bean创建实例之前和之后执行

postProcessBeforeInstantiation()方法分析

/**
	AbstractAutoProxyCreator中实现的了InstantiationAwareBeanPostProcessor接口,而下面的方法就是该接口提供的
	作用:
		postProcessBeforeInstantiation():在每一个Bean创建实例之前,调用该方法
*/
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    // 获取该bean的名称
   Object cacheKey = getCacheKey(beanClass, beanName);

   if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
       // 判断当前bean是不是需要增强的bean,第一次是没有的
      if (this.advisedBeans.containsKey(cacheKey)) {
         return null;
      }
       /**
       	isInfrastructureClass(beanClass):
       		里面有一条判断代码:
       		(super.isInfrastructureClass(beanClass) ||
				(this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
				
       		super.isInfrastructureClass(beanClass):用来判断该bean是不是基础类型Advice、Pointcut、Advisor、														AopInfrastructureBean
       		this.aspectJAdvisorFactory.isAspect(beanClass)):用来判断该bean是否有@Aspect注解(是不是切面类)
       */
      if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
         this.advisedBeans.put(cacheKey, Boolean.FALSE);
         return null;
      }
   }

   // Create proxy here if we have a custom TargetSource.
   // Suppresses unnecessary default instantiation of the target bean:
   // The TargetSource will handle target instances in a custom fashion.
   // 获取自定义的targetSource
   TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
   if (targetSource != null) {
      if (StringUtils.hasLength(beanName)) {
         this.targetSourcedBeans.add(beanName);
      }
      Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
      Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
      this.proxyTypes.put(cacheKey, proxy.getClass());
      return proxy;
   }

   return null;
}

在bean实例化前调用这个方法之后,后面会创建bean实例,然后对bean进行参数赋值populateBean(beanName, mbd, instanceWrapper),执行exposedObject = initializeBean(beanName, exposedObject, mbd)方法。

initializeBean(beanName, exposedObject, mbd)方法

/**
 * 初始化给定的bean实例,并且应用工厂回调init方法和bean后处理器。
 * 对于传统定义的bean,从{@link #createBean}调用,对于现有的bean实例,从{@link #initializeBean}调用。
 * @param beanName 工厂中的bean名称(用于调试)
 * @param bean 我们可能需要初始化的新bean实例
 * @param mbd 使用创建的bean的bean定义(如果给定了现有的bean实例,也可以是{@code null})
 * @return 初始化的bean实例(可能包装)
 * @see BeanNameAware
 * @see BeanClassLoaderAware
 * @see BeanFactoryAware
 * @see #applyBeanPostProcessorsBeforeInitialization
 * @see #invokeInitMethods
 * @see #applyBeanPostProcessorsAfterInitialization
 */
// 作用:初始化bean方法
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
   // java安全管理
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   }
   else {
      // 调用Aware方法:方法里面会判断bean是否实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口,如果实现则调用被重写的方法
      invokeAwareMethods(beanName, bean);
   }
   // 词语解析:wrapped 包裹、包装
   Object wrappedBean = bean;
   // 判断mbd==null || bean定义是否是“合成的”,即不是由应用程序本身定义的。
   if (mbd == null || !mbd.isSynthetic()) {
      /** 
      * 执行beanPostProcessors的postProcessBeforeInitialization()方法;
      * 
      * 作用:会在所有bean进行初始化之前调用所有的beanPostProcessors中的postProcessBeforeInitialization()方法;
      *
      * 具体代码步骤:
      		1、Object result = existingBean;
      		2、遍历所有beanPostProcessors,并调用其的postProcessBeforeInitialization()方法
      		3、return result;
      */
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      /*
      	现在,给一个bean一个机会来做出反应,它的所有属性都已设置,并有一个机会了解它拥有的bean工厂(此对象)。这意味着检查bean是否实现了InitializingBean或定义了一个自定义的init方法,并在调用时调用了必要的回调。
      	
      	作用:对bean进行初始化操作
      */
      invokeInitMethods(beanName, wrappedBean, mbd);
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
   }
   // 判断mbd==null || bean定义是否是“合成的”,即不是由应用程序本身定义的。
   if (mbd == null || !mbd.isSynthetic()) {
      /** 
      * 执行beanPostProcessors的postProcessAfterInitialization()方法;
      * 
      * 作用:会在所有bean进行初始化之前调用所有的beanPostProcessors中的postProcessAfterInitialization()方法;
      *
      * 具体代码步骤:
      		1、Object result = existingBean;
      		2、遍历所有beanPostProcessors,并调用其的postProcessAfterInitialization()方法
      		3、return result;
      */
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}

postProcessAfterInitialization(result, beanName)方法分析

/**
 * 如果bean被子类确定为要代理的对象,则用配置的拦截器创建一个代理。
 * @see #getAdvicesAndAdvisorsForBean
 */
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
   if (bean != null) {
      // 获取bean名称
      Object cacheKey = getCacheKey(bean.getClass(), beanName);
      if (this.earlyProxyReferences.remove(cacheKey) != bean) {// 如果需要的话就包装(创建代理对象)起来!!!!(获取到了一个给定bean的proxy代理对象)。需求:如果bean是需要被切入(增强)的组件
         return wrapIfNecessary(bean, beanName, cacheKey);
      }
   }
   return bean;
}

wrapIfNecessary(bean, beanName, cacheKey)方法分析

	/**
	 * 必要时包装给定的bean,即是否有资格被代理。
	 * @param bean the raw bean instance
	 * @param beanName the name of the bean
	 * @param cacheKey the cache key for metadata access
	 * @return a proxy wrapping the bean, or the raw bean instance as-is
	 */
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    // 判断已经增强的bean中有没有当前bean(advisedBeans)
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    }
    // 判断当前bean是不是基础类型(切面相关)/切面
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    // 如果我们有增强器(通知)的话,请创建代理。
    // 获取当前bean的增强器(通知方法):这里需要深度解析一下
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
       	// 为给定的bean创建一个AOP代理。
        Object proxy = createProxy(
            bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        // 将proxy代理对象添加到proxyTypes中
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}

Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null)在这句代码中,作用是获取了当前bean的所有增强器(通知方法),具体过程如下:

getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null)方法

@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
      Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
   // 查找符合条件(可用)的增强器(通知方法)
   List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
   if (advisors.isEmpty()) {
      return DO_NOT_PROXY;
   }
   return advisors.toArray();
}

findEligibleAdvisors(beanClass, beanName)方法

/**
 * 查找所有符合条件(可用)的增强器(通知方法)以自动代理该class
 * @param beanClass the clazz to find advisors for
 * @param beanName the name of the currently proxied bean
 * @return the empty List, not {@code null},
 * if there are no pointcuts or interceptors
 * @see #findCandidateAdvisors
 * @see #sortAdvisors
 * @see #extendAdvisors
 */
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
   // 单词扩展:candidate 候选者
   // 查找并获取所有候选器增强器(通知方法)
   List<Advisor> candidateAdvisors = findCandidateAdvisors();// 查找所有可以使用的增强器(通知方法)
   List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
   extendAdvisors(eligibleAdvisors);
   if (!eligibleAdvisors.isEmpty()) {
      eligibleAdvisors = sortAdvisors(eligibleAdvisors);
   }
   return eligibleAdvisors;
}

findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName)方法

/**
 * 搜索给定的候选Advisor(增强器(通知方法)),以查找可以应用于指定bean的所有Advisor(增强器(通知方法))。
 * @param candidateAdvisors the candidate Advisors
 * @param beanClass the target's bean class
 * @param beanName the target's bean name
 * @return the List of applicable Advisors
 * @see ProxyCreationContext#getCurrentProxiedBeanName()
 */
protected List<Advisor> findAdvisorsThatCanApply(
      List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
   // 设置bean名称
   ProxyCreationContext.setCurrentProxiedBeanName(beanName);
   try {
      // 查找所有可以使用在bean的增强器(通知方法)列表
      return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
   }
   finally {
      ProxyCreationContext.setCurrentProxiedBeanName(null);
   }
}

findAdvisorsThatCanApply(candidateAdvisors, beanClass)方法

/**
 * 确定{@code 候选通知}列表的子列表,该子列表适用于给定的class类。
 * @param candidateAdvisors the Advisors to evaluate
 * @param clazz the target class
 * @return sublist of Advisors that can apply to an object of the given class
 * (may be the incoming List as-is)
 */
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
   // 判断候选增强器(通知方法)列表是否为空
   if (candidateAdvisors.isEmpty()) {
      return candidateAdvisors;
   }
   // 遍历候选增强器列表,将可用在bean的增强器(通知方法)添加到eligibleAdvisors列表中
   List<Advisor> eligibleAdvisors = new ArrayList<>();
   for (Advisor candidate : candidateAdvisors) {
      if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
         eligibleAdvisors.add(candidate);
      }
   }
   boolean hasIntroductions = !eligibleAdvisors.isEmpty();
   for (Advisor candidate : candidateAdvisors) {
      // 判断候选增强器属不属于IntroductionAdvisor接口:不属于
      if (candidate instanceof IntroductionAdvisor) {
         // already processed
         continue;
      }
      /* 
      	判断候选增强器是不是可用的,如果是,将增强器添加到eligibleAdvisors列表中
      	canApply():用于判断增强器是否可以应用到给定的class类上。
      		内容:
      			if (advisor instanceof IntroductionAdvisor) {
                    return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
                }
                else if (advisor instanceof PointcutAdvisor) {
                	// 通过切入点表达式判断增强器是否可以用在指定class类的方法上
                    PointcutAdvisor pca = (PointcutAdvisor) advisor;
                    return canApply(pca.getPointcut(), targetClass, hasIntroductions);
                }
                else {
                    // It doesn't have a pointcut so we assume it applies.
                    return true;
                }
      */
      if (canApply(candidate, clazz, hasIntroductions)) {
         // 将可以用在指定class类的增强器添加到eligibleAdvisors列表中
         eligibleAdvisors.add(candidate);
      }
   }
   // 返回可应用于给定class类的对象的Advisor(增强器)列表
   return eligibleAdvisors;
}

Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean))方法:为给定的bean创建一个AOP代理

protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
      @Nullable Object[] specificInterceptors, TargetSource targetSource) {

   if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
      AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
   }

   ProxyFactory proxyFactory = new ProxyFactory();
   proxyFactory.copyFrom(this);

   if (!proxyFactory.isProxyTargetClass()) {
      if (shouldProxyTargetClass(beanClass, beanName)) {
         proxyFactory.setProxyTargetClass(true);
      }
      else {
         evaluateProxyInterfaces(beanClass, proxyFactory);
      }
   }

   // 对proxy进行一些初始化和自定义操作
   Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
   proxyFactory.addAdvisors(advisors);
   proxyFactory.setTargetSource(targetSource);
   customizeProxyFactory(proxyFactory);

   proxyFactory.setFrozen(this.freezeProxy);
   if (advisorsPreFiltered()) {
      proxyFactory.setPreFiltered(true);
   }
   // 返回给定bean的proxy代理
   return proxyFactory.getProxy(getProxyClassLoader());
}

proxyFactory.getProxy(getProxyClassLoader())方法

public Object getProxy(@Nullable ClassLoader classLoader) {
   		// 创建proxy代理对象并获取proxy代理对象
		return createAopProxy().getProxy(classLoader);
	}

getAopProxyFactory()方法

protected final synchronized AopProxy createAopProxy() {
   if (!this.active) {
      activate();
   }
   return getAopProxyFactory().createAopProxy(this);
}

getAopProxyFactory()方法

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
   if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
      Class<?> targetClass = config.getTargetClass();
      if (targetClass == null) {
         throw new AopConfigException("TargetSource cannot determine target class: " +
               "Either an interface or a target is required for proxy creation.");
      }
      if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
         // 如果目标有实现,使用jdk创建代理
         return new JdkDynamicAopProxy(config);
      }
      // 使用Cglib创建代理
      return new ObjenesisCglibAopProxy(config);
   }
   else {
      // 如果目标有实现,使用jdk创建代理
      return new JdkDynamicAopProxy(config);
   }
}

目标方法执行

bean.play();

在这里插入图片描述
ioc容器中存放着bean的代理对象,代理对象中保存了详细信息(增强器、增强对象…)。

创建拦截器链

chain:拦截器链。将每一个通知方法包装成为方法拦截器,利用MethodInterceptor的机制拦截切入点(被增强的方法)的,然后执行通知方法

intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)方法

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
   // 声明变量
   Object oldProxy = null;
   boolean setProxyContext = false;
   Object target = null;
   TargetSource targetSource = this.advised.getTargetSource();
   try {
      if (this.advised.exposeProxy) {
         // Make invocation available if necessary.
         oldProxy = AopContext.setCurrentProxy(proxy);
         setProxyContext = true;
      }
      // 获取要切入的目标对象
      target = targetSource.getTarget();
      Class<?> targetClass = (target != null ? target.getClass() : null);
      // 根据proxyFactory对象获取目标方法的拦截器链
      List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
      Object retVal;
      // Check whether we only have one InvokerInterceptor: that is,
      // no real advice, but just reflective invocation of the target.
      if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
         // We can skip creating a MethodInvocation: just invoke the target directly.
         // Note that the final invoker must be an InvokerInterceptor, so we know
         // it does nothing but a reflective operation on the target, and no hot
         // swapping or fancy proxying.
         Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
         retVal = methodProxy.invoke(target, argsToUse);
      }
      else {
         // We need to create a method invocation...
         retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
      }
      retVal = processReturnType(proxy, target, method, retVal);
      return retVal;
   }
   finally {
      if (target != null && !targetSource.isStatic()) {
         targetSource.releaseTarget(target);
      }
      if (setProxyContext) {
         // Restore old proxy.
         AopContext.setCurrentProxy(oldProxy);
      }
   }
}

this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass)方法

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
      Advised config, Method method, @Nullable Class<?> targetClass) {

   // This is somewhat tricky... We have to process introductions first,
   // but we need to preserve order in the ultimate list.
   // 声明变量
   AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
   Advisor[] advisors = config.getAdvisors();
   // 创建InterceptorList,并设置长度,长度为advisors.length所有增强器的个数(5)
   List<Object> interceptorList = new ArrayList<>(advisors.length);
   Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
   Boolean hasIntroductions = null;

   for (Advisor advisor : advisors) {
      if (advisor instanceof PointcutAdvisor) {
         // Add it conditionally.
         PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
         if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
            MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
            boolean match;
            if (mm instanceof IntroductionAwareMethodMatcher) {
               if (hasIntroductions == null) {
                  hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
               }
               match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
            }
            else {
               match = mm.matches(method, actualClass);
            }
            if (match) {
               // 获取MethodInterceptor数组,怎么获取呢?看下面
               MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
               if (mm.isRuntime()) {
                  // Creating a new object instance in the getInterceptors() method
                  // isn't a problem as we normally cache created chains.
                  for (MethodInterceptor interceptor : interceptors) {
                     interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
                  }
               }
               else {
                  interceptorList.addAll(Arrays.asList(interceptors));
               }
            }
         }
      }
      else if (advisor instanceof IntroductionAdvisor) {
         IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
         if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
            Interceptor[] interceptors = registry.getInterceptors(advisor);
            interceptorList.addAll(Arrays.asList(interceptors));
         }
      }
      else {
         Interceptor[] interceptors = registry.getInterceptors(advisor);
         interceptorList.addAll(Arrays.asList(interceptors));
      }
   }

   return interceptorList;
}

registry.getInterceptors(advisor)方法:获取MethodInterceptor数组

public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
   // 声明变量
   List<MethodInterceptor> interceptors = new ArrayList<>(3);
   Advice advice = advisor.getAdvice();
   /*
   判断当前advice(增强器)是不是属于XX类型
   */
   if (advice instanceof MethodInterceptor) {
      // 如果advice(增强器)是MethodInterceptor类型(是我们需要的类型),则直接添加到interceptors中
      interceptors.add((MethodInterceptor) advice);
   }
   // 如果advice(增强器)不是MethodInterceptor,则在循环中通过Adapter(适配器)将其包装成MethodInterceptor类型
   for (AdvisorAdapter adapter : this.adapters) {
      if (adapter.supportsAdvice(advice)) {
         /*
         里面的步骤:
         	1、通过advisor获取通知方法,强转为MethodBeforeAdvice/AfterReturningAdvice
         	2、return new MethodBeforeAdviceInterceptor(advice)/AfterReturningAdviceInterceptor(advice)
         */
         interceptors.add(adapter.getInterceptor(advisor));
      }
   }
   if (interceptors.isEmpty()) {
      throw new UnknownAdviceTypeException(advisor.getAdvice());
   }
   // 将interceptors转换为MethodInterceptor[]数组,并返回
   return interceptors.toArray(new MethodInterceptor[0]);
}

拦截器链(MethodInterceptor)获取+执行顺序

获取拦截器链的顺序 CglibMethodInvocation的**interceptorsAndDynamicMethodMatchers()**中的顺序一致。spring利用拦截器链来保证增强器(通知方法)的执行顺序。
在这里插入图片描述

步骤:

  1. 创建CglibMethodInvocation对象,调用它的==proceed()==方法。
  2. 调用super.proceed()
  3. 判断是否获取了所有的拦截器,如果没有,则按顺序获取拦截器,并调用拦截器的invoke();如果已经获取所有拦截器,则调用反射机制调用被增强的方法。
  4. ==拦截器.inboke()方法调用mi.proceed()==方法 —> super.proceed() ||开始循环|| ==拦截器.inboke()方法调用mi.proceed()==方法 —> super.proceed() ············

代码单词解析:

  • 拦截器中的.==invoke()==方法中的 mi = CglibMethodInvocation对象

注意:

  • 获取到MethodBeforeAdviceInterceptor前置通知时会先执行。this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
  • 被增强方法会在获取完所有拦截器后执行。return invokeJoinpoint();
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
   // 声明一些变量
   Object oldProxy = null;
   boolean setProxyContext = false;
   Object target = null;
   TargetSource targetSource = this.advised.getTargetSource();
   try {
      if (this.advised.exposeProxy) {
         // Make invocation available if necessary.
         oldProxy = AopContext.setCurrentProxy(proxy);
         setProxyContext = true;
      }
      // 获取要切入的目标类
      target = targetSource.getTarget();
      Class<?> targetClass = (target != null ? target.getClass() : null);
      // 创建拦截器链
      List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
      Object retVal;
      // 检查我们是否只有一个InvokerInterceptor:并不是一个真正的通知方法,而只是对目标的反射调用。
      if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
         // 我们可以跳过创建MethodInvocation的方法:直接调用目标即可。注意,最终的调用者必须是InvokerInterceptor,所以我们知道它仅对目标执行反射操作,并且不进行热交换或反射代理。
         Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
         retVal = methodProxy.invoke(target, argsToUse);
      }
      else {
         // 创建一个CglibMethodInvocation来进行调用(重点!!!!!)
         retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
      }
      retVal = processReturnType(proxy, target, method, retVal);
      return retVal;
   }
   finally {
      if (target != null && !targetSource.isStatic()) {
         targetSource.releaseTarget(target);
      }
      if (setProxyContext) {
         // Restore old proxy.
         AopContext.setCurrentProxy(oldProxy);
      }
   }
}

new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed()方法:获取拦截器链并按顺序执行

public Object proceed() throws Throwable {
   try {
      // 调用父类的proceed();CglibMethodInvocation的父类是ReflectiveMethodInvocation反射方法执行类
      return super.proceed();
   }
   catch (RuntimeException ex) {
      throw ex;
   }
   catch (Exception ex) {
      if (ReflectionUtils.declaresException(getMethod(), ex.getClass())) {
         throw ex;
      }
      else {
         throw new UndeclaredThrowableException(ex);
      }
   }
}

super.proceed() = ReflectiveMethodInvocation.proceed()

public Object proceed() throws Throwable {
   // 判断当前拦截器index是否与CglibMethodInvocation的拦截器List数组数量是否相同;如果相同,则调用反射机制执行被增强的方法
   if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
      return invokeJoinpoint();
   }
   // 从CglibMethodInvocation的拦截器List数组中获取一个拦截器
   Object interceptorOrInterceptionAdvice =
         this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
   // 判断拦截器是不是InterceptorAndDynamicMethodMatcher类型
   if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
      // Evaluate dynamic method matcher here: static part will already have
      // been evaluated and found to match.
      InterceptorAndDynamicMethodMatcher dm =
            (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
      Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
      if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
         return dm.interceptor.invoke(this);
      }
      else {
         // 动态匹配失败。跳过此拦截器并调用链中的下一个拦截器。
         return proceed();
      }
   }
   else {
      // 它是一个拦截器,因此我们只需要调用它的invoke()
      return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
   }
}

获取拦截器之后执行拦截器中的通知方法和被增强的方法:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值