Spring Aop之JDK方式创建代理类的源码思路
Posted javartisan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Aop之JDK方式创建代理类的源码思路相关的知识,希望对你有一定的参考价值。
import org.aopalliance.intercept.MethodInvocation;
import org.aopalliance.intercept.MethodInterceptor;
public class CustomMethodAdvice implements MethodInterceptor
@Override
public Object invoke(MethodInvocation invocation) throws Throwable
System.out.println("CustomMethodInterceptor Before !");
Object an = invocation.proceed();
System.out.println("CustomMethodInterceptor After !");
return an;
测试代码:
@Test
public void testProxyFactory()
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(new UserServiceImpl());
// 不设置接口的话使用CGLIB
proxyFactory.setInterfaces(UserService.class);
// 不指定Pointcut的话,默认是TrueMethodMatcher,即匹配所有方法
proxyFactory.addAdvice(new CustomMethodAdvice());
UserService us = (UserService) proxyFactory.getProxy();
System.out.println(us.login("daxin"));
saveClassFile(us.getClass(), "UserServiceProxy");
DecoratingProxy dp = (DecoratingProxy) us;
System.out.println(dp.getDecoratedClass());
Jdk生成的代理类继承结构:
接口作用:
UserService:目标对象的接口,用于生成相应类型的代理类。
SpringProxy:Spring代理类的标记接口,用于Spring内部判断对象是否是Spring代理
Advised:Spring Aop配置信息的持有对象
DecoratingProxy:用于获取目标对象的真是Class名字
生成代理对象的方法org.springframework.aop.framework.JdkDynamicAopProxy#getProxy(java.lang.ClassLoader):
@Override
public Object getProxy(ClassLoader classLoader)
// 根据advised信息获取代理类需要实现的接口,同时三个:SpringProxy,Advised以及目标对象接口
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
// 校验是否自定义实现了equals与hashCode方法
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
//生成代理类,this对象包含了整个Aop的配置信息
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
当代理对象进行方法调用时候会触发org.springframework.aop.framework.JdkDynamicAopProxy#invoke方法:
/**
* Implementation of @code InvocationHandler.invoke.
* <p>Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
@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]);
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method))
// The target does not implement the hashCode() method itself.
return hashCode();
// 由于代理类实现了: 目标对象接口, SpringProxy, Advised, DecoratingProxy等接口,因此方法调用时候必须按照类型进行特殊处理
//1:Advised类型处理
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;
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.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);
/**
* Implementation of @code InvocationHandler.invoke.
* <p>Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
@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
// equals与hashCode方法调用处理
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();
// 由于代理类实现了: 目标对象接口, SpringProxy, Advised, DecoratingProxy等接口,因此方法调用时候必须按照类型进行特殊处理
//1:DecoratingProxy类型方法调用
else if (method.getDeclaringClass() == DecoratingProxy.class)
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
// 2: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;
//是否开启对象设置到当前上下文中,开启的话可以进行设置
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.
// 获取当前方法的增强逻辑,根据的是MethodMatcher组件为依据
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...
// 将调用信息封装成MethodInvocation信息,然后进行反射调用
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);
到此就完成了方法的调用。
以上是关于Spring Aop之JDK方式创建代理类的源码思路的主要内容,如果未能解决你的问题,请参考以下文章
Spring读源码系列之AOP--08--aop执行完整源码流程之自动代理创建器导入的两种方式
Spring读源码系列之AOP--06---AopProxy===>spring使用jdk和cglib生成代理对象的终极奥义
Spring框架系列(10) - Spring AOP实现原理详解之AOP代理的创建