说完了AOP代理对象的建立,事务代理对象的建立,这文,讲讲AOP代理对象执行java
在静态代理与JDK动态代理与CGLIB动态代理这一节咱们讲过:spring
$Proxy0
形式的代理类,$Proxy0
方法,内部调用父类Proxy.InvocationHandler.invoke方法
UserNoInterface$$EnhancerByCGLIB$$b3361405
形式的代理类xxx$$EnhancerByCGLIB$$b3361405
代理类方法,内部调用MethodInterceptor.intercept()
SpringAop是经过JDK动态代理或者CGLB动态代理实现的,他也会有如上特征。缓存
注意: 此处的MethodInterceptor是CGLB中的。 区别于AOP联盟中的MethodInterceptor
app
下面逐个分析代理的执行。ide
JDK动态代理执行:代理类方法-->InvocationHandler.invoke()-->目标方法 JdkDynamicAopProxy 是JDK动态代理的实现类。 JdkDynamicAopProxy自己是一个InvocationHandler,因此咱们执行代理的某个方法时,会通过JdkDynamicAopProxy.invoke方法而后去调用目标方法。post
@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种状况:this
重点看看第三种状况:spa
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方法,执行目标方法。