默认情况下,当一个 bean 继承了一个或多个接口的时候,Spring 就会使用 JDK 动态代理
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
Assert.notNull(config, "AdvisedSupport must not be null");
if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
throw new AopConfigException("No advisors and no TargetSource specified");
}
// advised 就是 ProxyFactory 对象
this.advised = config;
// 获取生成代理对象所需要实现的接口,同时还包括 Spring 自己添加的三个接口:SpringProxy,Advised,DecoratingProxy
this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
// 判断这些方法中有没有定义 equals 和 hashCode 方法
findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
// this.proxiedInterfaces: 获取生成代理对象所需要实现的接口
// this: 就是 JdkDynamicAopProxy,因为 JdkDynamicAopProxy 实现了 InvocationHandler
// 针对所指定的接口生成代理对象,包括用户所添加的接口以及 SpringProxy,Advised,DecoratingProxy
// 所以生成的代理对象可以强制转换为任一个接口类型
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// ...
}
}
1、准备代理
JDK 动态代理除了会添加我们自己的接口外,还会添加三个 Spring 自己的接口:SpringProxy,Advised,DecoratingProxy
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
Assert.notNull(config, "AdvisedSupport must not be null");
if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
throw new AopConfigException("No advisors and no TargetSource specified");
}
// advised 就是 ProxyFactory 对象
this.advised = config;
// 获取生成代理对象所需要实现的接口,同时还包括 Spring 自己添加的三个接口:SpringProxy,Advised,DecoratingProxy
this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
// 判断这些方法中有没有定义 equals 和 hashCode 方法
findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}
2、代理类
调用代理逻辑 Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
这里的 this 就是 JdkDynamicAopProxy
,因为 JdkDynamicAopProxy
实现了 InvocationHandler
接口
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
// this.proxiedInterfaces: 获取生成代理对象所需要实现的接口
// this: 就是 JdkDynamicAopProxy,因为 JdkDynamicAopProxy 实现了 InvocationHandler
// 针对所指定的接口生成代理对象,包括用户所添加的接口以及 SpringProxy,Advised,DecoratingProxy
// 所以生成的代理对象可以强制转换为任一个接口类型
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
3、执行代理逻辑
当代理调用调用某个方法的时候,就会进入 invoke 方法中
@Override
@Nullable
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;
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;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
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);
// 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);
}
}
}