Spring|Spring AOP从原理到源码(四)
上一节Spring AOP从原理到源码(三)讲述了代理对象的创建过程,本小节关注方法调用的拦截过程。
2. 调用方法的拦截
调用方法拦截主要是将创建阶段中加入的Advisor
(或者Advice
等)转换成拦截器(MethodInterceptor
)链,然后利用责任链模式,逐个调用拦截器链中的拦截器,对被代理方法进行增强。
下面我们来看看调用了proxy.doService
方法后会发生什么。
这里我们只关注JdkDynamicAopProxy
产生的代理对象,通过Cglib产生的代理对象同理,读者举一反三即可,不做赘述。
我们都知道,当代理对象被拦截时,都会调用InvocationHandler#invoke
方法,所以我们关注JdkDynamicAopProxy#invoke
,这段代码内容很多,关注有注释的地方即可。
/**
* Implementation of {@code InvocationHandler.invoke}.
* Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
// 从配置里把封装了目标对象的TargetSource拿出来
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.
// 获取拦截器链,还记得在创建代理对象过程中的advisors吗?
// 这里就是把advisors中会拦截现在这个方法(method)的Advisor封装成List
/**
* 什么叫会拦截现在这个方法?
*还记得PointcutAdvisor吗?里面有ClassFilter和MethodMatcher,用来匹配是否需要拦截
*/
List
这个方法我们重点关注3个地方:
- 拦截器链的获取;
- 责任链(
MethodInvocation
)的构建。 - 责任链的执行,即目标方法执行过程中的增强。
/**
* Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects
* for the given method, based on this configuration.
* @param method the proxied method
* @param targetClass the target class
* @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
*/
public List
为了读者思路的流畅性,如果还没很明白前面说的内容,下面这段可以先不看,先把流程理顺
这里多说一下从
advisor
中获取interceptors
的方法(DefaultAdvisorAdapterRegistry#getInterceptors
)中的适配器模式。对于
Advice
来说,有很多种:BeforAdvice
、AfterAdvice
、ThrowsAdvice
……在实现上,也有非常多的实现:AbstractAspectJAdvice
及其子类,Interceptor
及其子类……如果把这些统一起来,封装到MethodInterceptor
里,就需要适配器了。可以看到DefaultAdvisorAdapterRegistry
在构造方法中添加了3种适配器:MethodBeforeAdviceAdapter
、AfterReturningAdviceAdapter
、ThrowsAdviceAdapter
。下面具体看看
adapter#getInterceptor
做了什么,以MethodBeforeAdviceAdapter
为例:
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
// 如果advice属于MethodBeforAdvice就能支持,才能调用下面的getInterceptor方法
return (advice instanceof MethodBeforeAdvice);
}@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
// 把advice封装起来,待调用的时候使用
return new MethodBeforeAdviceInterceptor(advice);
}
} new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain)
这个方法就是构建责任链,源码没什么特别的,不做特别说明。
invocation.proceed()
责任链的执行,很明显就是把上面的拦截器一个个拿出来,调用
MethodInterceptor#invoke
方法@Override
@Nullable
public Object proceed() throws Throwable {
//We start with an index of -1 and increment early.
// 所有MethodInterceptor都遍历完了,直接调用目标方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}// 获取到下一个待调用是拦截器(MethodInterceptor)
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// 如果是动态的拦截器(即MethodMather#isRuntime == true的)还要根据传入方法的参数来拦截
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.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.
// 调用MethodInterceptor#invoke
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
这个方法的逻辑就是,拦截器链还有没执行完的就拿出来继续调用
invoke
方法,执行完了就直接调用被代理对象的目标方法。重点看看
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
(注意这里传入了this
,也就是把ReflectiveMethodInvocation
实例又传进去了),以MethodBeforeAdviceInterceptor#invoke
为例`:// MethodBeforeAdviceInterceptor.java
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// 真正的方法增强在这里完成
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
// 推进到下一个MethodInterceptor执行,mi就是之前传进来的this,也就是ReflectiveMethodInvocation,所以又会回到ReflectiveMethodInvocation#proceed
// 大白话就是:触发下一个拦截器,或者调用目标方法
return mi.proceed();
}
通过这个方法可以看到,调用了之后又会回到
ReflectiveMethodInvocation#proceed
方法继续执行链式调用,一直到最后调用目标方法。至此,拦截过程执行完毕。
源码总结 通过看源码,可以得出结论:
-
ProxyFactory
核心就是两段:
- 创建代理对象
- 拦截过程中的调用链执行
- 对于代理对象的创建,其实就是把
Advisor(s)
和目标对象封装在一起 - 对于拦截过程,就是把
Advisor(s)
转换成List
,然后封装成责任链(ReflectiveMethodInvocation
),通过ReflectiveMethodInvocation#proceed
方法推进拦截器(MethodInterceptor#invoke
)的执行,最后是目标方法。 - 所以对读者来说,只要清楚的核心过程,又知道里面出现的
Advice
、Advisor
、Pointcut
、MethodInterceptor
、MethodInvocation
分别是什么,理解源码完全没有难度。
小结 文章讲到这里,相信大家对spring aop的核心过程已经有所了解了,对于
ProxyFactoryBean
,先简单讲讲原理,未来有时间的话再考虑写文章分析,主要是原理都一样的,看到这里读者应该都有能力分析。ProxyFactory
和ProxyFactoryBean
的最大区别就是前者是编程式创建代理,而后者是声明式的创建代理,如果了解spring里的FactoryBean
就知道了,直接看ProxyFactoryBean#getObject
方法即可。对于完成的spring aop流程,无非就是封装了
ProxyFactory
,没有什么特别的,在容器启动的时候,创建bean,然后通过后置处理器看看是否需要代理,需要代理的话,找到它的切面(Advisor
),然后创建代理。就这么简单。总结 总结一下Spring AOP的学习方法。所谓“授人以鱼不如授人以渔”,之前所看的所有文章都在讲源码,讲得都挺好,我开始看这个的时候也是这么看源码的,能看懂,但不深刻,大概是方法还不够到位。其实spring aop的源码也不算很难,掌握了学习方法和一些对应的设计模式(内功)即可。
下面说说个人认为比较好的学习方法,如果大家有好的方法,也欢迎不吝赐教。
- 了解核心类:
Advice
、Pointcut
、Advisor
、PointcutAdvisor
、Interceptor
,及其对应的继承关系; - 知道aop的两个核心过程:代理创建过程、方法调用拦截过程。
- 从
ProxyFactory
开始看起、从ProxyFactory
开始看起、从ProxyFactory
开始看起。 - 最后看
ProxyFactoryBean
(这是ProxyFactory
+FactoryBean
的结合)和EnableAspectJAutoProxy
(这是对ProxyFactory
的封装)。
推荐阅读
- Docker应用:容器间通信与Mariadb数据库主从复制
- 一个人的碎碎念
- 我从来不做坏事
- 由浅入深理解AOP
- Activiti(一)SpringBoot2集成Activiti6
- 从蓦然回首到花开在眼前,都是为了更好的明天。
- 西湖游
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 改变自己,先从自我反思开始