Spring AOP源码分析& 时序图 非原创- 2021-01-03 14:43- spring: Spring AOP 时序图


AOP必须要知道的概念

1、切面(Aspect)面向规则,具有相同规则的方法的集合体
2、通知(Advice)回调
3、切入点(Pointcut)需要代理的具体方法
4、目标对象(Target Object)被代理的对象
5、AOP代理(AOP Proxy)主要两种方式:JDK、CGLib
6、前置通知(Before Advice)在invoke Pointcut之前调用,织入的方法
7、后置通知(After Advice)Pointcut之后调用,织入的方法
8、返回后通知(After Return Advice)返回值为非Void,织入的方法
9、环绕通知(Around Advice)只要触发调用,织入的方法
10、异常通知(After Throwing Advice)Pointcut抛出异常,织入的方法

Spring AOP 源码分析

源码理解可以分为4部分,依次是:
寻找入口 -> 选择策略 -> 调用方法 -> 触发通知

一 寻找入口

Spring 的 AOP 是通过接入 BeanPostProcessor 后置处理器开始的,它是 Spring IOC 容器经常使用到 的一个特性,这个 Bean 后置处理器是一个监听器,可以监听容器触发的 Bean 声明周期事件。后置处 理器向容器注册以后,容器中管理的 Bean 就具备了接收 IOC 容器事件回调的能力。BeanPostProcessor 的使用非常简单,只需要提供一个实现接口 BeanPostProcessor 的实现类,然后在 Bean 的配置文件中设置即可。

1、BeanPostProcessor

  1. public interface BeanPostProcessor {
  2. //为在Bean的初始化前提供回调入口
  3. @Nullable
  4. default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  5. return bean;
  6. }
  7. //为在Bean的初始化之后提供回调入口
  8. @Nullable
  9. default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  10. return bean;
  11. }
  12. }

这两个回调的入口都是和容器管理的 Bean 的生命周期事件紧密相关,可以为用户提供在 Spring IOC 容器初始化 Bean 过程中自定义的处理操作。

2、AbstractAutowireCapableBeanFactory 类对容器生成的 Bean 添加后置处理器

BeanPostProcessor 后置处理器的调用发生在 Spring IOC 容器完成对 Bean 实例对象的创建和属性的依赖注入完成之后,在对Spring依赖注入的源码分析过程中我们知道,当应用程序第一次调用 getBean()方法(lazy-init 预实例化除外)向 Spring IOC 容器索取指定 Bean 时触发 Spring IOC 容器创建 Bean 实例 对 象 并 进 行 依 赖 注 入 的 过 程 , 其 中 真 正 实 现 创 建 Bean 对 象 并 进 行 依 赖 注 入 的 方 法 是AbstractAutowireCapableBeanFactory 类的 doCreateBean()方法,主要源码如下:

  1. public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
  2. implements AutowireCapableBeanFactory {
  3. //真正创建Bean的方法
  4. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  5. throws BeanCreationException {
  6. //创建 Bean 实例对象
  7. ...
  8. //Bean对象的初始化,依赖注入在此触发
  9. //这个exposedObject在初始化完成之后返回作为依赖注入完成后的Bean
  10. Object exposedObject = bean;
  11. try {
  12. //将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象
  13. populateBean(beanName, mbd, instanceWrapper);
  14. //初始化Bean对象
  15. exposedObject = initializeBean(beanName, exposedObject, mbd);
  16. }
  17. catch (Throwable ex) {
  18. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  19. throw (BeanCreationException) ex;
  20. }
  21. else {
  22. throw new BeanCreationException(
  23. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  24. }
  25. }
  26. ...
  27. //为应用返回所需要的实例对象
  28. return exposedObject;
  29. }

从上面的代码中我们知道,为 Bean 实例对象添加 BeanPostProcessor 后置处理器的入口的是 initializeBean()方法。

3、initializeBean()方法为容器产生的 Bean 实例对象添加 BeanPostProcessor 后置处理器

同样在 AbstractAutowireCapableBeanFactory 类中,initializeBean()方法实现为容器创建的 Bean实例对象添加 BeanPostProcessor 后置处理器,源码如下:

  1. //初始容器创建的Bean实例对象,为其添加BeanPostProcessor后置处理器
  2. protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  3. //JDK的安全机制验证权限
  4. if (System.getSecurityManager() != null) {
  5. //实现PrivilegedAction接口的匿名内部类
  6. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  7. invokeAwareMethods(beanName, bean);
  8. return null;
  9. }, getAccessControlContext());
  10. }
  11. else {
  12. //为Bean实例对象包装相关属性,如名称,类加载器,所属容器等信息
  13. invokeAwareMethods(beanName, bean);
  14. }
  15. Object wrappedBean = bean;
  16. //对BeanPostProcessor后置处理器的postProcessBeforeInitialization
  17. //回调方法的调用,为Bean实例初始化前做一些处理
  18. if (mbd == null || !mbd.isSynthetic()) {
  19. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  20. }
  21. //调用Bean实例对象初始化的方法,这个初始化方法是在Spring Bean定义配置
  22. //文件中通过init-method属性指定的
  23. try {
  24. invokeInitMethods(beanName, wrappedBean, mbd);
  25. }
  26. catch (Throwable ex) {
  27. throw new BeanCreationException(
  28. (mbd != null ? mbd.getResourceDescription() : null),
  29. beanName, "Invocation of init method failed", ex);
  30. }
  31. //对BeanPostProcessor后置处理器的postProcessAfterInitialization
  32. //回调方法的调用,为Bean实例初始化之后做一些处理
  33. if (mbd == null || !mbd.isSynthetic()) {
  34. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  35. }
  36. return wrappedBean;
  37. }
  38. @Override
  39. //调用BeanPostProcessor后置处理器实例对象初始化之前的处理方法
  40. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  41. throws BeansException {
  42. Object result = existingBean;
  43. //遍历容器为所创建的Bean添加的所有BeanPostProcessor后置处理器
  44. for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
  45. //调用Bean实例所有的后置处理中的初始化前处理方法,为Bean实例对象在
  46. //初始化之前做一些自定义的处理操作
  47. Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
  48. if (current == null) {
  49. return result;
  50. }
  51. result = current;
  52. }
  53. return result;
  54. }
  55. @Override
  56. //调用BeanPostProcessor后置处理器实例对象初始化之后的处理方法
  57. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  58. throws BeansException {
  59. Object result = existingBean;
  60. //遍历容器为所创建的Bean添加的所有BeanPostProcessor后置处理器
  61. for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
  62. //调用Bean实例所有的后置处理中的初始化后处理方法,为Bean实例对象在
  63. //初始化之后做一些自定义的处理操作
  64. Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
  65. if (current == null) {
  66. return result;
  67. }
  68. result = current;
  69. }
  70. return result;
  71. }

BeanPostProcessor 是一个接口,其初始化前的操作方法和初始化后的操作方法均委托其实现子类来实现,在 Spring 中,BeanPostProcessor 的实现子类非常的多,分别完成不同的操作,如:AOP 面向切面编程的注册通知适配器、Bean 对象的数据校验、Bean 继承属性、方法的合并等等,我们以最简单的AOP 切面织入来简单了解其主要的功能。下面我们来分析其中一个创建 AOP 代理对象的子类AbstractAutoProxyCreator 类。该类重写了 postProcessAfterInitialization()方法。

二、选择代理策略

1、进入postProcessAfterInitialization()方法

进入 postProcessAfterInitialization()方法,我们发现调到了一个非常核心的方法 wrapIfNecessary(),其源码如下:

  1. public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
  2. implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
  3. @Override
  4. public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
  5. if (bean != null) {
  6. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  7. if (!this.earlyProxyReferences.contains(cacheKey)) {
  8. return wrapIfNecessary(bean, beanName, cacheKey);
  9. }
  10. }
  11. return bean;
  12. }
  13. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
  14. if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
  15. return bean;
  16. }
  17. // 判断是否不应该代理这个 bean
  18. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
  19. return bean;
  20. }
  21. /**
  22. *判断是否是一些 InfrastructureClass 或者是否应该跳过这个 bean。
  23. * 所谓 InfrastructureClass 就是指 Advice/PointCut/Advisor 等接口的实现类。
  24. * shouldSkip 默认实现为返回 false,由于是 protected 方法,子类可以覆盖。
  25. */
  26. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
  27. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  28. return bean;
  29. }
  30. // 获取这个 bean 的 advice
  31. // Create proxy if we have advice.
  32. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  33. if (specificInterceptors != DO_NOT_PROXY) {
  34. this.advisedBeans.put(cacheKey, Boolean.TRUE);
  35. // 创建代理
  36. Object proxy = createProxy(
  37. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
  38. this.proxyTypes.put(cacheKey, proxy.getClass());
  39. return proxy;
  40. }
  41. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  42. return bean;
  43. }
  44. protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
  45. @Nullable Object[] specificInterceptors, TargetSource targetSource) {
  46. if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
  47. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
  48. }
  49. ProxyFactory proxyFactory = new ProxyFactory();
  50. proxyFactory.copyFrom(this);
  51. if (!proxyFactory.isProxyTargetClass()) {
  52. if (shouldProxyTargetClass(beanClass, beanName)) {
  53. proxyFactory.setProxyTargetClass(true);
  54. } else {
  55. evaluateProxyInterfaces(beanClass, proxyFactory);
  56. }
  57. }
  58. Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
  59. proxyFactory.addAdvisors(advisors);
  60. proxyFactory.setTargetSource(targetSource);
  61. customizeProxyFactory(proxyFactory);
  62. proxyFactory.setFrozen(this.freezeProxy);
  63. if (advisorsPreFiltered()) {
  64. proxyFactory.setPreFiltered(true);
  65. }
  66. return proxyFactory.getProxy(getProxyClassLoader());
  67. }
  68. }

2、获取代理对象

整个过程跟下来,发现最终调用的是 proxyFactory.getProxy()方法。到这里我们大概能够猜到proxyFactory 有 JDK 和 CGLib 的,那么我们该如何选择呢?最终调用的是 DefaultAopProxyFactory的 createAopProxy()方法:

  1. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
  2. @Override
  3. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  4. if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
  5. Class<?> targetClass = config.getTargetClass();
  6. if (targetClass == null) {
  7. throw new AopConfigException("TargetSource cannot determine target class: " +
  8. "Either an interface or a target is required for proxy creation.");
  9. }
  10. if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
  11. return new JdkDynamicAopProxy(config);
  12. }
  13. return new ObjenesisCglibAopProxy(config);
  14. }
  15. else {
  16. return new JdkDynamicAopProxy(config);
  17. }
  18. }
  19. private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
  20. Class<?>[] ifcs = config.getProxiedInterfaces();
  21. return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
  22. }
  23. }

三、调用代理方法

分析调用逻辑之前先上类图,看看 Spring 中主要的 AOP 组件:
image.png
上面我们已经了解到 Spring 提供了两种方式来生成代理方式有 JDKProxy 和 CGLib。下面我们来研究 一下 Spring 如何使用 JDK 来生成代理对象,具体的生成代码放在 JdkDynamicAopProxy 这个类中, 直接上相关代码:

  1. final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
  2. /**
  3. * 获取代理类要实现的接口,除了Advised对象中配置的,还会加上SpringProxy, Advised(opaque=false)
  4. * 检查上面得到的接口中有没有定义 equals或者hashcode的接口
  5. * 调用Proxy.newProxyInstance创建代理对象
  6. */
  7. @Override
  8. public Object getProxy(@Nullable ClassLoader classLoader) {
  9. if (logger.isDebugEnabled()) {
  10. logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
  11. }
  12. Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
  13. findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
  14. return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
  15. }
  16. }

通过注释我们应该已经看得非常明白代理对象的生成过程,此处不再赘述。下面的问题是,代理对象生 成了,那切面是如何织入的?
我们知道 InvocationHandler 是 JDK 动态代理的核心,生成的代理对象的方法调用都会委托到 InvocationHandler.invoke()方法。而从 JdkDynamicAopProxy 的源码我们可以看到这个类其实也实现了 InvocationHandler,下面我们分析 Spring AOP 是如何织入切面的,直接上源码看 invoke()方法:

  1. final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
  2. /**
  3. * Implementation of {@code InvocationHandler.invoke}.
  4. * <p>Callers will see exactly the exception thrown by the target,
  5. * unless a hook method throws an exception.
  6. */
  7. @Override
  8. @Nullable
  9. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  10. MethodInvocation invocation;
  11. Object oldProxy = null;
  12. boolean setProxyContext = false;
  13. TargetSource targetSource = this.advised.targetSource;
  14. Object target = null;
  15. try {
  16. //eqauls()方法,具目标对象未实现此方法
  17. if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
  18. // The target does not implement the equals(Object) method itself.
  19. return equals(args[0]);
  20. }
  21. //hashCode()方法,具目标对象未实现此方法
  22. else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
  23. // The target does not implement the hashCode() method itself.
  24. return hashCode();
  25. }
  26. else if (method.getDeclaringClass() == DecoratingProxy.class) {
  27. // There is only getDecoratedClass() declared -> dispatch to proxy config.
  28. return AopProxyUtils.ultimateTargetClass(this.advised);
  29. }
  30. //Advised接口或者其父接口中定义的方法,直接反射调用,不应用通知
  31. else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
  32. method.getDeclaringClass().isAssignableFrom(Advised.class)) {
  33. // Service invocations on ProxyConfig with the proxy config...
  34. return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
  35. }
  36. Object retVal;
  37. if (this.advised.exposeProxy) {
  38. // Make invocation available if necessary.
  39. oldProxy = AopContext.setCurrentProxy(proxy);
  40. setProxyContext = true;
  41. }
  42. // Get as late as possible to minimize the time we "own" the target,
  43. // in case it comes from a pool.
  44. //获得目标对象的类
  45. target = targetSource.getTarget();
  46. Class<?> targetClass = (target != null ? target.getClass() : null);
  47. // Get the interception chain for this method.
  48. //获取可以应用到此方法上的Interceptor列表
  49. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
  50. // Check whether we have any advice. If we don't, we can fallback on direct
  51. // reflective invocation of the target, and avoid creating a MethodInvocation.
  52. //如果没有可以应用到此方法的通知(Interceptor),此直接反射调用 method.invoke(target, args)
  53. if (chain.isEmpty()) {
  54. // We can skip creating a MethodInvocation: just invoke the target directly
  55. // Note that the final invoker must be an InvokerInterceptor so we know it does
  56. // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
  57. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
  58. retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
  59. }
  60. else {
  61. // We need to create a method invocation...
  62. //创建MethodInvocation
  63. invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
  64. // Proceed to the joinpoint through the interceptor chain.
  65. retVal = invocation.proceed();
  66. }
  67. // Massage return value if necessary.
  68. Class<?> returnType = method.getReturnType();
  69. if (retVal != null && retVal == target &&
  70. returnType != Object.class && returnType.isInstance(proxy) &&
  71. !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
  72. // Special case: it returned "this" and the return type of the method
  73. // is type-compatible. Note that we can't help if the target sets
  74. // a reference to itself in another returned object.
  75. retVal = proxy;
  76. }
  77. else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
  78. throw new AopInvocationException(
  79. "Null return value from advice does not match primitive return type for: " + method);
  80. }
  81. return retVal;
  82. }
  83. finally {
  84. if (target != null && !targetSource.isStatic()) {
  85. // Must have come from TargetSource.
  86. targetSource.releaseTarget(target);
  87. }
  88. if (setProxyContext) {
  89. // Restore old proxy.
  90. AopContext.setCurrentProxy(oldProxy);
  91. }
  92. }
  93. }
  94. }

主要实现思路可以简述为:首先获取应用到此方法上的通知链(Interceptor Chain)。如果有通知,则 应用通知,并执行 JoinPoint;如果没有通知,则直接反射执行 JoinPoint。而这里的关键是通知链是如 何获取的以及它又是如何执行的呢?现在来逐一分析。首先,从上面的代码可以看到,通知链是通过 Advised.getInterceptorsAndDynamicInterceptionAdvice()这个方法来获取的,我们来看下这个方法 的实现逻辑:

  1. public class AdvisedSupport extends ProxyConfig implements Advised {
  2. public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
  3. MethodCacheKey cacheKey = new MethodCacheKey(method);
  4. List<Object> cached = this.methodCache.get(cacheKey);
  5. if (cached == null) {
  6. cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
  7. this, method, targetClass);
  8. this.methodCache.put(cacheKey, cached);
  9. }
  10. return cached;
  11. }
  12. }

通过上面的源码我们可以看到,实际获取通知的实现逻辑其实是由 AdvisorChainFactory 的getInterceptorsAndDynamicInterceptionAdvice()方法来完成的,且获取到的结果会被缓存。下面来分析 getInterceptorsAndDynamicInterceptionAdvice()方法的实现:

  1. public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {
  2. /**
  3. * 从提供的配置实例config中获取advisor列表,遍历处理这些advisor.如果是IntroductionAdvisor,
  4. * 则判断此Advisor能否应用到目标类targetClass上.如果是PointcutAdvisor,则判断
  5. * 此Advisor能否应用到目标方法method上.将满足条件的Advisor通过AdvisorAdaptor转化成Interceptor列表返回.
  6. */
  7. @Override
  8. public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
  9. Advised config, Method method, @Nullable Class<?> targetClass) {
  10. // This is somewhat tricky... We have to process introductions first,
  11. // but we need to preserve order in the ultimate list.
  12. List<Object> interceptorList = new ArrayList<>(config.getAdvisors().length);
  13. Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
  14. //查看是否包含IntroductionAdvisor
  15. boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
  16. //这里实际上注册一系列AdvisorAdapter,用于将Advisor转化成MethodInterceptor
  17. AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
  18. for (Advisor advisor : config.getAdvisors()) {
  19. if (advisor instanceof PointcutAdvisor) {
  20. // Add it conditionally.
  21. PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
  22. if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
  23. //这个地方这两个方法的位置可以互换下
  24. //将Advisor转化成Interceptor
  25. MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
  26. //检查当前advisor的pointcut是否可以匹配当前方法
  27. MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
  28. if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
  29. if (mm.isRuntime()) {
  30. // Creating a new object instance in the getInterceptors() method
  31. // isn't a problem as we normally cache created chains.
  32. for (MethodInterceptor interceptor : interceptors) {
  33. interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
  34. }
  35. }
  36. else {
  37. interceptorList.addAll(Arrays.asList(interceptors));
  38. }
  39. }
  40. }
  41. }
  42. else if (advisor instanceof IntroductionAdvisor) {
  43. IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
  44. if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
  45. Interceptor[] interceptors = registry.getInterceptors(advisor);
  46. interceptorList.addAll(Arrays.asList(interceptors));
  47. }
  48. }
  49. else {
  50. Interceptor[] interceptors = registry.getInterceptors(advisor);
  51. interceptorList.addAll(Arrays.asList(interceptors));
  52. }
  53. }
  54. return interceptorList;
  55. }
  56. }

这个方法执行完成后,Advised 中配置能够应用到连接点(JoinPoint)或者目标类(Target Object)的 Advisor 全部被转化成了 MethodInterceptor,接下来我们再看下得到的拦截器链是怎么起作用的:

  1. final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  3. ...
  4. //如果没有可以应用到此方法的通知(Interceptor),此直接反射调用 method.invoke(target, args)
  5. if (chain.isEmpty()) {
  6. // We can skip creating a MethodInvocation: just invoke the target directly
  7. // Note that the final invoker must be an InvokerInterceptor so we know it does
  8. // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
  9. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
  10. retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
  11. }
  12. else {
  13. // We need to create a method invocation...
  14. //创建MethodInvocation
  15. invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
  16. // Proceed to the joinpoint through the interceptor chain.
  17. retVal = invocation.proceed();
  18. }
  19. ...
  20. }
  21. }

从 这 段 代 码 可 以 看 出 , 如 果 得 到 的 拦 截 器 链 为 空 , 则 直 接 反 射 调 用 目 标 方 法 , 否 则 创 建MethodInvocation,调用其 proceed()方法,触发拦截器链的执行,来看下具体代码:

  1. public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
  2. @Override
  3. @Nullable
  4. public Object proceed() throws Throwable {
  5. // We start with an index of -1 and increment early.
  6. //如果Interceptor执行完了,则执行joinPoint
  7. if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
  8. return invokeJoinpoint();
  9. }
  10. Object interceptorOrInterceptionAdvice =
  11. this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
  12. //如果要动态匹配joinPoint
  13. if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
  14. // Evaluate dynamic method matcher here: static part will already have
  15. // been evaluated and found to match.
  16. InterceptorAndDynamicMethodMatcher dm =
  17. (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
  18. //动态匹配:运行时参数是否满足匹配条件
  19. if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
  20. return dm.interceptor.invoke(this);
  21. }
  22. else {
  23. // Dynamic matching failed.
  24. // Skip this interceptor and invoke the next in the chain.
  25. //动态匹配失败时,略过当前Intercetpor,调用下一个Interceptor
  26. return proceed();
  27. }
  28. }
  29. else {
  30. // It's an interceptor, so we just invoke it: The pointcut will have
  31. // been evaluated statically before this object was constructed.
  32. //执行当前Intercetpor
  33. return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
  34. }
  35. }
  36. }

至此,通知链就完美地形成了。我们再往下来看 invokeJoinpointUsingReflection()方法,其实就是反 射调用:

  1. public abstract class AopUtils {
  2. @Nullable
  3. public static Object invokeJoinpointUsingReflection(@Nullable Object target, Method method, Object[] args)
  4. throws Throwable {
  5. // Use reflection to invoke the method.
  6. try {
  7. ReflectionUtils.makeAccessible(method);
  8. return method.invoke(target, args);
  9. }
  10. catch (InvocationTargetException ex) {
  11. // Invoked method threw a checked exception.
  12. // We must rethrow it. The client won't see the interceptor.
  13. throw ex.getTargetException();
  14. }
  15. catch (IllegalArgumentException ex) {
  16. throw new AopInvocationException("AOP configuration seems to be invalid: tried calling method [" +
  17. method + "] on target [" + target + "]", ex);
  18. }
  19. catch (IllegalAccessException ex) {
  20. throw new AopInvocationException("Could not access method [" + method + "]", ex);
  21. }
  22. }
  23. }

Spring AOP 源码就分析到这儿

时序图

image.png
**