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增强的逻辑
//注意这里直接调用的target,即真实对象
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
这里面有两个重要的方法:
- getInterceptorsAndDynamicInterceptionAdvice: 从Advised里找到合适的Advice,并通过适配器转换成MethodInteceptor。只与为什么会有Advice,可以参考Spring AOP(3)基于XML理解代理类的创建
- ReflectiveMethodInvocation: 将proxy和真是对象,以及method,Advice的数组包装成ReflectiveMethodInvocation,调用内部的proceed()方法进行增强。
1)getInterceptorsAndDynamicInterceptionAdvice
//Determine a list of MethodInterceptor objects for the given method, based on this configuration.
public List
2)ReflectiveMethodInvocation的使用
//ReflectiveMethodInvocation是调用interceptor的地方
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
//当interceptorsAndDynamicMethodMatchers数量为1的时候,invokeJoinpoint就是直接通过反射调用真实的方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
//从0开始一个个拿Interceptor
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
//如果是InterceptorAndDynamicMethodMatcher,mm.isRuntime()这种情况才会封装InterceptorAndDynamicMethodMatcher
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
Class> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
//如果MethodMatcher验证成功,就调用interceptor
if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
//如果验证失败就跳过,递归下一个
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
//就直接是intercepto,就直接invoke这个MethodInterceptor
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
MethodBeforeAdviceInterceptor类似这种,内部会调用advice的方法,然调用mi.proceed()进入递归。
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {
private final MethodBeforeAdvice advice;
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
}
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
}
}