文章预览
AOP的最后一步,就是代理类的调用了,这里我们以JdkDynamicAopProxy为例,首先我们先回顾一下JAVA动态代理。
JAVA动态代理
定义一个接口Interface和实现类RealSubject,通过实现InvocationHandler接口的invoke()提供代理类的方法。
interface Subject{
void sayName();
}
public class RealSubject implements Subject{
@Override
public void sayName() {
System.out.println("real subject say...");
}
}
//创建动态代理
Subject realSubject = new RealSubject();
//一定是接口类型
Subject proxySubject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),
realSubject.getClass().getInterfaces(),
(proxy, method, args1) -> {
System.out.println("before proxy invoke...");
Object invoke = method.invoke(realSubject);
System.out.println("before proxy invoke...");
return invoke;
});
proxySubject.sayName();
==============================
before proxy invoke...
real subject say...
before proxy invoke...
使用JDK动态代理一定要使用接口,并且提供InvocationHandler接口的实现。
如何查看这个生成的动态代理的类?
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true"); 加上这句话,生成动态代理的时候会在idea的工作目录下生成com/sun/proxy/$Proxy0.class类
newProxyInstance()方法 主要是通过getProxyClass0()来生成代理对象的并且有一个ProxyClassCache缓存对象WeakCache,这里面又通过ProxyGenetor类来进行代理对象生成。
从下面生成代码中可见,生成的Proxy对象继承了Proxy并实现了需要代理的类Subject,Proxy里面有成员变量InvocationHandler h,所以生成的代理对象需要通过构造函数传入InvocationHandler。
同时,会默认代理equals(), toString(), hashCode() 方法
public final class $Proxy0 extends Proxy implements Subject {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
//这个代理类是需要传入InvocationHandler作为构造函数
//继承了Proxy并实现了需要代理的类
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final void sayName() throws {
try {
//调用代理类的sayName,这里就通过invocationhandler的invoke方法进行增强。
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.refinitiv.edp.boomi.sw.sqs.listener.Subject").getMethod("sayName");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
JdkDynamicAopProxy的invoke
JdkDynamicAopProxy本身实现了InvocationHandler,所以需要关注它的invoke()方法,如何来进行增强的。
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
//targetSource包含了realSubject,即真实对象
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
//如果美标方法没有重写equals,这里处理equals方法
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
//如果美标方法没有重写hashcode,这里处理hashcode方法
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
//如果declaringClass是getDecoratedClass类型的
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
//这里直接通过反射调用method,不需要走下面advice增强的逻辑
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;
这个Advised是不是需要暴露出去,即用ThreadLocal包装一下,放到AopContext里
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是真正的对象
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// Get the interception chain for this method.
//这个是核心方法,就是从Advised里面获取所有的Advisor,然后通过AdvisorAdapterRegistry将Advisor里的advice转换成MethodInteceptor
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.
//如果没有找到增强的Advice,就直接invoke method
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 {
//如果找到合适的Advice,转成MethodInteceptor,然后包装成ReflectiveMethodInvocation,调用proceed();
// 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);
}
}
}
这里面有两个重要的方法:
-
从Advised里找到合适的Advice,并通过适配器转换成MethodInteceptor。只与为什么会有Advice,可以参考
Spring AOP(3)基于XML理解代理类的创建
-
将proxy和真是对象,以及method,Advice的数组包装成ReflectiveMethodInvocation,调用内部的proceed()方法进行增强。
1)getInterceptorsAndDynamicInterceptionAdvice
2)ReflectiveMethodInvocation的使用
………………………………