說完了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方法,執行目標方法。