说完了AOP代理对象的创建,事务代理对象的创建,这文,讲讲AOP代理对象执行
在 静态代理与JDK动态代理与CGLIB动态代理 这一节我们讲过:
$Proxy0
形式的代理类, $Proxy0
方法,内部调用父类 Proxy.InvocationHandler.invoke方法
UserNoInterface$$EnhancerByCGLIB$$b3361405
形式的代理类 xxx$$EnhancerByCGLIB$$b3361405
代理类方法,内部调用 MethodInterceptor.intercept()
SpringAop是通过JDK动态代理或者CGLB动态代理实现的,他也会有如上特征。
注意: 此处的MethodInterceptor是CGLB中的。 区别于AOP联盟中的MethodInterceptor
下面逐个分析代理的执行。
JDK动态代理执行:代理类方法-->InvocationHandler.invoke()-->目标方法 JdkDynamicAopProxy 是JDK动态代理的实现类。 JdkDynamicAopProxy本身是一个InvocationHandler,所以我们执行代理的某个方法时,会经过JdkDynamicAopProxy.invoke方法然后去调用目标方法。
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { MethodInvocation invocation; Object oldProxy = null; boolean setProxyContext = false; TargetSource targetSource = this.advised.targetSource; Class<?> targetClass = null; Object target = null; try { 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(); } else if (method.getDeclaringClass() == DecoratingProxy.class) { // There is only getDecoratedClass() declared -> dispatch to proxy config. return AopProxyUtils.ultimateTargetClass(this.advised); } else if (!this.advised.opaque && method.getDeclaringClass().isInterface() && method.getDeclaringClass().isAssignableFrom(Advised.class)) { // Service invocations on ProxyConfig with the proxy config... return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args); } Object retVal; //是否暴露代理对象,如果暴露就把当前代理对象放到AopContext上下文中, //这样在本线程的其他地方也可以获取到代理对象了。 if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy = AopContext.setCurrentProxy(proxy); setProxyContext = true; } // May be null. Get as late as possible to minimize the time we "own" the target, // in case it comes from a pool. target = targetSource.getTarget(); if (target != null) { targetClass = target.getClass(); } // Get the interception chain for this method. 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. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse); } else { // 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(); } // Massage return value if necessary. Class<?> returnType = method.getReturnType(); if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { // Special case: it returned "this" and the return type of the method // is type-compatible. Note that we can't help if the target sets // a reference to itself in another returned object. retVal = proxy; } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) { throw new AopInvocationException( "Null return value from advice does not match primitive return type for: " + method); } return retVal; } finally { if (target != null && !targetSource.isStatic()) { // Must have come from TargetSource. targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } } 复制代码
这里分为3种情况:
重点看看第三种情况:
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) { MethodCacheKey cacheKey = new MethodCacheKey(method); List<Object> cached = this.methodCache.get(cacheKey); if (cached == null) { cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice( this, method, targetClass); this.methodCache.put(cacheKey, cached); } return cached; } 复制代码
这里也用了缓存设计,如果缓存中为null。则使用DefaultAdvisorChainFactory工厂类获取增强器链chain。 获取的原理: 遍历所有适用当前类的Advisor,通过AdvisorAdapterRegistry适配器,将Advisor的每一个Advice,适配成MethodInterceptor。
接下来,就是处理返回值。
至此:AOP-JDK动态代理的执行就完成。
调用方法-->动态代理.方法-->InvocationHandler.invoke-->MethodInvocation.proceed执行增强器链-->Adivce.invoke方法-->目标方法
CGLB动态代理执行:代理类方法-->MethodInterceptor.intercept()-->目标方法
CglibAopProxy是CGLB动态代理的实现类。
CglibAopProxy会创建一个DynamicAdvisedInterceptor来拦截目标方法的执行。 DynamicAdvisedInterceptor
实现了 MethodInterceptor
。当我们执行代理的某个方法时,会经过DynamicAdvisedInterceptor.intercept()方法然后去调用目标方法。
我们看看这个方法
@Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { Object oldProxy = null; boolean setProxyContext = false; Class<?> targetClass = null; Object target = null; try { if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy = AopContext.setCurrentProxy(proxy); setProxyContext = true; } // May be null. Get as late as possible to minimize the time we // "own" the target, in case it comes from a pool... target = getTarget(); if (target != null) { targetClass = target.getClass(); } 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) { releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } } 复制代码
可以看出跟AOP-CGLB动态代理与AOP-JDK动态 有很多相似之处。
至此:AOP-CGLB动态代理的执行就完成。
调用方法-->动态代理类.方法-->MethodInterceptor.intercept方法-->MethodInvocation.proceed执行增强器链-->Adivce.invoke方法-->目标方法
springaop是基于jdk动态代理与cglb动态代理。
springAop把拦截器封装成Advice,组成Advice链。封装到MethodInterceptor或者InvocationHandler中。当调用方法时,都会先调用代理类方法,经过增强器链的调用每个Adivce.invoke方法,执行目标方法。