AopProxy 的两个子类 CglibAopProxy 、 JdkDynamicAopProxy 分别采用不同的方式产生代理对象
AopProxy 是 通过 AopProxyFactory 来生成的
DefaultAopProxyFactory.createAopProxy 方法 根据 AdvisedSupport 生成AopProxy 这里决定了使用CGLIB还是Jdk的的方式
在生成 Proxy之前,首先需要从advised对象中获取代理对象的代理接口配置,然后调用 Proxy的newProxyInstance 方法,最终得到 Proxy 代理对象,在生成代理对象时,需要指定三个参数,一个时类加载器,一个是代理接口,一个是Proxy回调方法所在的对象,这个对象需要实现InvocationHandler接口,这个接口顶一个 invoke方法,提供代理对象的回调入口。对于 JdkDynamicAopProxy 他本身实现了 InvocationHandler接口的 invoke 方法,这个回调接口完成了AOP编织实现的封装。
构造方法主要是 this.advised = config; 保存配置信息
// 为给定的AOP配置构造一个新的JdkDynamicAopProxy。
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");
}
// config 里包含了 advice 和 pointCut
this.advised = config;
this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
// 判断是否重新定义了 hashCode 和 equals 方法
findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}
获取一个代理对象
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
//使用 jdk 的Proxy 生成代理对象 // this 实现了 InvocationHandler接口
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
实现了invoke接口完成了 代理对象的目标方法的执行流程 其中真正的拦截器链拦截的现实 通过
MethodInvocation 来完成
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 {
// 代理目标没有重写 equals
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
// 代理目标没有重写 hashCode
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
// 只有getDecoratedClass()声明->分派到代理配置。
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
//如果目标对象是Advice类型,则直接使用反射进行调用
//opaque-->标记是否需要阻止通过该配置创建的代理对象转换为Advised类型,默认值为false,表示代理对象可以被转换为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;
// 判断是否需要用 AopContext 或者 threadLock 暴漏出去
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); // 获取目标对象的类类型
//获取此方法的拦截链。
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.
//我们可以跳过创建MethodInvocation:直接调用目标
//请注意,最后一个调用程序必须是InvokerInterceptor,因此我们知道它是这样的
//只有对目标的反射操作,没有热交换或奇特的代理。
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// 否则创建 MethodInvocation 执行拦截调用
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, 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);
}
}
}
递归调用 proceed 保证 advice 都被执行 采用 currentInterceptorIndex 计数 保证 每个拦截器只执行一次 并且 invokeJoinpoint也只执行一次 执行 invokeJoinpoint 过程中能够 其他 advice 可能没有执行完全
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
// 我们从指数-1开始,并提前递增。 递归调用 所有拦截器链中的 Matcher 的 advice
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
// 运行目标对象的方法 也就是反射调用的指定目标
return invokeJoinpoint();
}
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// 判断advice 是不是 InterceptorAndDynamicMethodMatcher 的子类 则 advice 有 match的English
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());
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.
// 它是一个拦截器,直接调用 他的 invoke方法 可能是Interceptor 的 invoke 也有可能是 advice 的 invoke
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
CglibAopProxy 通过 intercept进行拦截
也是通过 CglibMethodInvocation 执行 目标方法与拦截器