Spring AOP源码解析(中)

  • Post author:
  • Post category:其他


上一篇文章中,介绍了Spring中动态代理的使用方式,通过ProxyFactory来创建代理对象,ProxyFactory可以通过addAdvisor()来添加匹配逻辑和代理逻辑,这篇文章重点介绍ProxyFactory是如何产生代理对象以及代理对象是如何执行代理逻辑的



一、ProxyFactory生成代理对象

使用ProxyFactory添加advisor,并创建代理对象,调用代理对象的test()方法,代码如下:


BeforeAdvisor:

public class LizhiBeforeAdvisor implements PointcutAdvisor {
	@Override
	public Advice getAdvice() {
		return new LizhiBeforeAdvice();
	}

	@Override
	public boolean isPerInstance() {
		return false;
	}

	@Override
	public Pointcut getPointcut() {
		return Pointcut.TRUE;
	}
}

public class LizhiBeforeAdvice implements MethodBeforeAdvice {
	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("before");
	}
}


LizhiAroundAdvisor



LizhiAfterReturningAdvisor

与上面

BeforeAdvisor

逻辑基本类似

重点介绍getProxy()方法

UserService target = new UserService();

ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(target);
proxyFactory.addAdvisor(new LizhiBeforeAdvisor());
proxyFactory.addAdvisor(new LizhiAroundAdvisor());
proxyFactory.addAdvisor(new LizhiAfterReturningAdvisor());
UserService userService = (UserService) proxyFactory.getProxy();
userService.test();


1.1 生成AopProxy

在生成代理对象之前,需要判断使用哪种代理方式来生成代理对象,JDK或CGLIB

public Object getProxy() {
    return createAopProxy().getProxy();
}

protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    // 默认为DefaultAopProxyFactory
    return getAopProxyFactory().createAopProxy(this);
}

NativeDetector.inNativeImage()用于判断当前程序是否运行在GraalVM上(类似JVM),如果是着这种情况,就只能只用JDK动态代理

config对象就是ProxyFactory对象,isOptimize()判断是否需要进行优化,较早的版本,CGLIB的效率比JDK要好,可以通过设置ProxyFactory的optimize等于true来使用CGLIB

isProxyTargetClass()判断是否为类进行代理,如果为true,即使被代理类实现了接口,也会使用CGLIB进行代理

hasNoUserSuppliedProxyInterfaces()用于判断是否添加了接口,如果没有添加接口,则使用CGLIB

只满足上面这些条件,还不能直接使用CGLIB,还需要判断被代理的类是否为接口,如果是接口,则使用JDK动态代理;或者被代理类本身就是一个JDK代理类,也将使用JDK动态代理;

只有不满足上前上个条件时,才会使用CGLIB进行代理;其他情况都使用JDK进行动态代理

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
   if (!NativeDetector.inNativeImage() &&
         (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)) {
         return new JdkDynamicAopProxy(config);
      }
      return new ObjenesisCglibAopProxy(config);
   }
   else {
      return new JdkDynamicAopProxy(config);
   }
}


1.2 生成代理对象

生成AopProxy后就可以去生成代理对象了

JDK生成代理对象:

public Object getProxy(@Nullable ClassLoader classLoader) {
   if (logger.isTraceEnabled()) {
      logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
   }
   // this实现了InvocationHandler
   return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}

CGLIB生成代理对象:

主要通过Enhancer来生成被代理类的代理类和代理对象,与JDK不同的点就在于不仅会生成一个代理对象,还会生成一个代理类

// 被代理的类
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

Class<?> proxySuperClass = rootClass;
// 如果被代理类本身就已经是Cglib所生成的代理类了
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
    // 获取真正的被代理类
    proxySuperClass = rootClass.getSuperclass();
    // 获取被代理类所实现的接口
    Class<?>[] additionalInterfaces = rootClass.getInterfaces();
    for (Class<?> additionalInterface : additionalInterfaces) {
        this.advised.addInterface(additionalInterface);
    }
}

// Validate the class, writing log messages as necessary.
validateClassIfNecessary(proxySuperClass, classLoader);

// Configure CGLIB Enhancer...
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
    enhancer.setClassLoader(classLoader);
    if (classLoader instanceof SmartClassLoader &&
        ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
        enhancer.setUseCache(false);
    }
}

// 被代理类,代理类的父类
enhancer.setSuperclass(proxySuperClass);
// 代理类额外要实现的接口
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));

// 获取和被代理类所匹配的Advisor
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
    types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
    this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);

// Generate the proxy class and create a proxy instance.
return createProxyClassAndInstance(enhancer, callbacks);



二、执行代理逻辑

以JDK动态代理为例:

在调用代理对象的方法时,会进入到InvocationHandler的invoke()方法,而JdkDynamicAopProxy本身实现了InvocationHandler接口



2.1 不执行代理逻辑

如果接口中没有定义equals()和hashCode(),但代理对象调用了这两个方法,就直接执行这个方法,不执行代理逻辑

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object oldProxy = null;
    boolean setProxyContext = false;

    // 拿到备代理对象
    TargetSource targetSource = this.advised.targetSource;
    Object target = null;

    // 如果接口中没有定义equals()方法,那么则直接调用,不走代理
    if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
        // The target does not implement the equals(Object) method itself.
        return equals(args[0]);
    }
    else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
        // The target does not implement the hashCode() method itself.
        return hashCode();
    }
    ……
}


2.2 ThreadLocal设置代理对象

如果ProxyFactory的exposeProxy为true,则把当前的代理对象设置到当前线程的ThreadLocal中,业务代码中可以通过AopContext.currentProxy()获取到当前类的代理对象,可以用于解决事务方法调用时事务失效的问题

private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal<>("Current AOP proxy");

if (this.advised.exposeProxy) {
    // Make invocation available if necessary.
    oldProxy = AopContext.setCurrentProxy(proxy);
    setProxyContext = true;
}

static Object setCurrentProxy(@Nullable Object proxy) {
    Object old = currentProxy.get();
    if (proxy != null) {
        currentProxy.set(proxy);
    }
    else {
        currentProxy.remove();
    }
    return old;
}


2.3 获取所有匹配的Advice

通过getInterceptorsAndDynamicInterceptionAdvice()获取所有与当前类的当前方法匹配的Advice

// 被代理对象和代理类
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);

// Get the interception chain for this method.
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

先从缓存methodCache中去取,把method封装成MethodCacheKey,作为缓存的Key,如果缓存中没有,则通过getInterceptorsAndDynamicInterceptionAdvice()去获取

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
   MethodCacheKey cacheKey = new MethodCacheKey(method);

   // 注意这个List,表示的就是Advice链
   List<Object> cached = this.methodCache.get(cacheKey);
   if (cached == null) {
      cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
            this, method, targetClass);
      this.methodCache.put(cacheKey, cached);
   }
   return cached;
}

ProxyFactory会把添加的advice都封装成advisor,然后遍历advisor进行匹配,主要通过Pointcut的逻辑进行匹配

@Override
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();
    // 从ProxyFactory中拿到所设置的Advice(添加时被封装成了DefaultPointcutAdvisor)
    // 添加的时候会控制顺序
    Advisor[] advisors = config.getAdvisors();
    List<Object> interceptorList = new ArrayList<>(advisors.length);
    Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
    Boolean hasIntroductions = null;
	……
    return interceptorList;
}


lizhiBeforeAdvisor:

public class LizhiBeforeAdvisor implements PointcutAdvisor {
   @Override
   public Advice getAdvice() {
      return new LizhiBeforeAdvice();
   }

   @Override
   public boolean isPerInstance() {
      return false;
   }

   @Override
   public Pointcut getPointcut() {
      return new Pointcut() {
         @Override
         public ClassFilter getClassFilter() {
            return new ClassFilter() {
               @Override
               public boolean matches(Class<?> clazz) {
                  return clazz.equals(UserService.class);
               }
            };
         }

         @Override
         public MethodMatcher getMethodMatcher() {
            return new MethodMatcher() {
               @Override
               public boolean matches(Method method, Class<?> targetClass) {
                  return false;
               }

               @Override
               public boolean isRuntime() {
                  return false;
               }

               @Override
               public boolean matches(Method method, Class<?> targetClass, Object... args) {
                  return false;
               }
            };
         }
      };
   }
}

遍历所有advisor进行匹配

根据上面定义的advisor,结合下面的匹配逻辑,可以清楚的看到,首先判断根据ClassFilter的matches()方法判断当前Advisor与当前类是否匹配,如果为true再进行方法匹配

先判断matches(Method method, Class<?> targetClass)是否匹配,如果为true,将Advisor封装成为MethodInterceptor,在真正执行Advisor的代理逻辑时,都是执行MethodInterceptor的invoke()方法里面的逻辑

再判断isRuntime()是否为true时,说明在调用方法时,还需要进行参数匹配,所以将isRuntime()为true的advisor封装成为InterceptorAndDynamicMethodMatcher,在真正调用时,还会调用matches(Method method, Class<?> targetClass, Object… args)方法进行校验

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) {
            // 如果匹配则将Advisor封装成为Interceptor,当前Advisor中的Advice可能即是MethodBeforeAdvice,也是ThrowsAdvice
            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));
            }
         }
      }
   }
    ……
}


2.3.1 Advisor封装成MethodInterceptor
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);

如果Advice实现的是MethodInterceptor接口,则直接添加到interceptors

如果Advice是实现的Advice接口,则通过AdvisorAdapter进行适配,主要包括MethodBeforeAdviceAdapter、AfterReturningAdviceAdapter和ThrowsAdviceAdapter

public DefaultAdvisorAdapterRegistry() {
    registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
    registerAdvisorAdapter(new AfterReturningAdviceAdapter());
    registerAdvisorAdapter(new ThrowsAdviceAdapter());
}

public void registerAdvisorAdapter(AdvisorAdapter adapter) {
    this.adapters.add(adapter);
}

public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
    List<MethodInterceptor> interceptors = new ArrayList<>(3);
    Advice advice = advisor.getAdvice();
    if (advice instanceof MethodInterceptor) {
        interceptors.add((MethodInterceptor) advice);
    }
    // 将Advice适配成MethodInterceptor
    for (AdvisorAdapter adapter : this.adapters) {
        if (adapter.supportsAdvice(advice)) {
            interceptors.add(adapter.getInterceptor(advisor));
        }
    }
    if (interceptors.isEmpty()) {
        throw new UnknownAdviceTypeException(advisor.getAdvice());
    }
    return interceptors.toArray(new MethodInterceptor[0]);
}

通过AdvisorAdapter的supportsAdvice()方法进行适配,以MethodBeforeAdviceAdapter为例:

如果advice实现了MethodBeforeAdvice接口,返回true,然后调用getInterceptor()方法,将MethodBeforeAdvice封装成一个MethodBeforeAdviceInterceptor

class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {

   @Override
   public boolean supportsAdvice(Advice advice) {
      return (advice instanceof MethodBeforeAdvice);
   }

   @Override
   public MethodInterceptor getInterceptor(Advisor advisor) {
      MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
      return new MethodBeforeAdviceInterceptor(advice);
   }

}


2.4 执行代理逻辑

当匹配所有的Advisor之后,没有像匹配的,则直接调用invokeJoinpointUsingReflection()方法

如果有相匹配的Advisor,则生成MethodInvocation对象,然后调用其proceed()方法

List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
if (chain.isEmpty()) {
   // 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.
   // 如果没有Advice,则直接调用对应方法
   Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
   retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
   // We need to create a method invocation...
   MethodInvocation invocation =
         new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
   // Proceed to the joinpoint through the interceptor chain.
   retVal = invocation.proceed();
}

currentInterceptorIndex初始值为-1,每调用一个MethodInterceptor就会加1,按照Advisor添加的顺序,开始执行Advisor的代理逻辑

如果当前的MethodInterceptor为InterceptorAndDynamicMethodMatcher,需要调用matches(this.method, targetClass, this.arguments)进行参数匹配,匹配成功调用invoke()方法,匹配不成功,则递归调用,获取下一个MethodInterceptor,进行判断。

注意,invoke(this)的入参为当前类对象,会形成递归调用,相当于一条chain

public Object proceed() throws Throwable {

   // We start with an index of -1 and increment early.
   // 当调用完了最后一个interceptor后就会执行被代理方法
   if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
      return invokeJoinpoint();
   }

   Object interceptorOrInterceptionAdvice =
         this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);

   // 当前interceptor是InterceptorAndDynamicMethodMatcher,则先进行匹配,匹配成功后再调用该interceptor
   // 如果没有匹配则递归调用proceed()方法,调用下一个interceptor
   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 {
         // Dynamic matching failed.
         // Skip this interceptor and invoke the next in the chain.
         // 不匹配则执行下一个MethodInterceptor
         return proceed();
      }
   }
   else {

      // It's an interceptor, so we just invoke it: The pointcut will have
      // been evaluated statically before this object was constructed.
      // 直接调用MethodInterceptor,传入this,在内部会再次调用proceed()方法进行递归
      // 比如MethodBeforeAdviceInterceptor
      return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
   }
}

以MethodBeforeAdviceInterceptor为例:

调用MethodBeforeAdviceInterceptor的invoke()方法时,会先去执行before()方法的逻辑,然后再递归调用proceed()方法

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {

   private final MethodBeforeAdvice advice;


   /**
    * Create a new MethodBeforeAdviceInterceptor for the given advice.
    * @param advice the MethodBeforeAdvice to wrap
    */
   public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
      Assert.notNull(advice, "Advice must not be null");
      this.advice = advice;
   }


   @Override
   @Nullable
   public Object invoke(MethodInvocation mi) throws Throwable {
      this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
      return mi.proceed();
   }

}

在CGLIB中,执行逻辑同JDK,CGLIB是在DynamicAdvisedInterceptor的intercept()方法中去匹配Advisor,然后封装成CglibMethodInvocation,调用proceed()方法,CglibMethodInvocation实现了ReflectiveMethodInvocation,所以proceed()与JDK的proceed()是同一个方法



版权声明:本文为sermonlizhi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。