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<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);
//这里直接通过反射调用method,不需要走下面advice增强的逻辑
//注意这里直接调用的target,即真实对象
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);
}
}
}
这里面有两个重要的方法:
- 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<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {
//call advisorChainFactory to get the inteceptor list
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
this, method, targetClass);
this.methodCache.put(cacheKey, cached);
}
return cached;
}
//use DefaultAdvisorChainFactory to get the Interceptor list
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class<?> targetClass) {
// This is somewhat tricky... We have to process introductions first,
// but we need to preserve order in the ultimate list.
//AdvisorAdapterRegistry提供了默认的AdvisorAdapterRegistry
//默认提供了MethodBeforeAdviceAdapter,AfterReturningAdviceAdapter,ThrowsAdviceAdapter
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
//拿到AdvisedSupport添加的advisor的数组
Advisor[] advisors = config.getAdvisors();
List<Object> interceptorList = new ArrayList<>(advisors.length);
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
Boolean hasIntroductions = null;
//遍历advisor
for (Advisor advisor : advisors) {
//如果Advisor是PointcutAdvisor
if (advisor instanceof PointcutAdvisor) {
// Add it conditionally.
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
//验证pointCut的class是不是对的
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
//拿到PointCut的MethodMatcher
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
boolean match;
//如果MethodMatcher是IntroductionAwareMethodMatcher类型的
if (mm instanceof IntroductionAwareMethodMatcher) {
if (hasIntroductions == null) {
//在检查一下actualClass
hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
}
//通过matchs方法检查method是不是匹配的
match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
}
//如果是普通类型的,就直接MethodMatcher.match()验证
else {
match = mm.matches(method, actualClass);
}
if (match) {
//如果找到匹配的,就通过registry来将advisor转换成MethodInterceptor
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
if (mm.isRuntime()) {
// Creating a new object instance in the getInterceptors() method
// isn't a problem as we normally cache created chains.
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
//如果是IntroductionAdvisor,调用这个类型的matches
else if (advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
//如果不是上面两种类型的Advisor,就直接获取Interceptor
else {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
return interceptorList;
}
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();
}
}