SpringAop源码情操陶冶-JdkDynamicAopProxy
承接前文SpringAop源码情操陶冶-AspectJAwareAdvisorAutoProxyCreator,本文在前文的基础上稍微简单的分析默认情况下的AOP代理,即JDK静态代理
JdkDynamicAopProxy#getProxy()-获取代理对象
首先我们先看下JDK代理是如何创建代理对象的,直接端上源码
@Override
public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
// 获取指定beanClass上的所有接口
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
// 简单查询下代理的接口有无定义了equals和hashCode方法
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
// 熟悉的套路以及配方
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
上述源码还是很简单的对需要代理的接口进行获取并创建我们熟知的JDK代理
JdkDynamicAopProxy#invoke()-拦截相应的接口方法
我们直接切入JDK代理的直接调用方法invoke()
,端上源码
/**
* Implementation of {@code InvocationHandler.invoke}.
* <p>Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Class<?> targetClass = null;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
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;
}
// May be null. Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
// Get the interception chain for this method.
// 关注点1,获取Advice集合,类似于拦截器的概念
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()) {
// 拦截器为空则直接调用方法
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// We need to create a method invocation...
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
// 关注点2,使用ReflectiveMethodInvocation来返回具体对象
retVal = invocation.proceed();
}
// Massage return value if necessary.
// 以下我们也可以忽略
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target && 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);
}
}
}
上述的源码内容过多,我们可以省略掉一些细则的代码,直接查看其关键的代码,针对上面的标注,我们主要关注两点:
AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice()
获取Advise集合,也就是类似于拦截器集合ReflectiveMethodInvocation#proceed()
根据上述的拦截器集合,执行真正的代理逻辑
AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice()-获取拦截器集合
里面的代码涉及了简单的缓存,为了节省用餐时间,我们直接去看关键类的关键方法DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice()
,直接上菜
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, Class<?> targetClass) {
// This is somewhat tricky... We have to process introductions first,
// but we need to preserve order in the ultimate list.
List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
// 遍历bean工厂中已创建的Advisor集合
for (Advisor advisor : config.getAdvisors()) {
if (advisor instanceof PointcutAdvisor) {
// Add it conditionally.
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
if (mm.isRuntime()) {
// 创建InterceptorAndDynamicMethodMatcher包装对象
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
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));
}
}
else {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
return interceptorList;
}
上述的代码认真分析的话比较复杂,简单粗略的看之我们可以得到要么会创建InterceptorAndDynamicMethodMatcher
包装对象,要么会直接获取Interceptor
对象。前者主要应用在下文的proceed()
方法
ReflectiveMethodInvocation#proceed()-执行真正的代理逻辑
直接把源码端上
@Override
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
// 直接执行,此时已遍历完内部的所有拦截器集合
return invokeJoinpoint();
}
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
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.
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
其实到上述这段代码,读者可以稍微关注下,每个MethodInterceptor
都会传入this
这个对象,如果稍微跟踪下就会发现,其实都是采用try-catch
机制,内部会继续调用本类的proceed()
方法,类似于递归的思想。而try-catch
机制恰好反映了before/after/around
等aop思想。
小结
AOP代理主要是获取对应bean的beanClass绑定的
Advice
集合,而此集合类似于拦截器针对拦截器的遍历,AOP是采用了递归的思想来遍历
ReflectiveMethodInvocation#proceed()
方法来实现而对相同类型的
Advice
,比如AspectJAfterAdvice
,有无执行的先后顺序,读者可自行查阅
SpringAop源码情操陶冶-JdkDynamicAopProxy的更多相关文章
- SpringAop源码情操陶冶-AspectJAwareAdvisorAutoProxyCreator
本文将对SpringAop中如何为AspectJ切面类创建自动代理的过程作下简单的分析,阅读本文前需要对AOP的Spring相关解析有所了解,具体可见Spring源码情操陶冶-AOP之ConfigBe ...
- Spring源码情操陶冶-AOP之ConfigBeanDefinitionParser解析器
aop-Aspect Oriented Programming,面向切面编程.根据百度百科的解释,其通过预编译方式和运行期动态代理实现程序功能的一种技术.主要目的是为了程序间的解耦,常用于日志记录.事 ...
- SpringMVC源码情操陶冶-FreeMarker之web配置
前言:本文不讲解FreeMarkerView视图的相关配置,其配置基本由FreeMarkerViewResolver实现,具体可参考>>>SpringMVC源码情操陶冶-ViewRe ...
- Spring源码情操陶冶-AbstractApplicationContext#finishBeanFactoryInitialization
承接前文Spring源码情操陶冶-AbstractApplicationContext#registerListeners 约定web.xml配置的contextClass为默认值XmlWebAppl ...
- Spring源码情操陶冶-AbstractApplicationContext#registerListeners
承接前文Spring源码情操陶冶-AbstractApplicationContext#onRefresh 约定web.xml配置的contextClass为默认值XmlWebApplicationC ...
- Spring源码情操陶冶-AbstractApplicationContext#onRefresh
承接前文Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster 约定web.xml配置的contextClass ...
- Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster
承接前文Spring源码情操陶冶-AbstractApplicationContext#initMessageSource 约定web.xml配置的contextClass为默认值XmlWebAppl ...
- Spring源码情操陶冶-AbstractApplicationContext#initMessageSource
承接前文Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors 约定web.xml配置的contextClass为默认值X ...
- Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors
承接前文Spring源码情操陶冶-AbstractApplicationContext#invokeBeanFactoryPostProcessors 瞧瞧官方注释 /** * Instantiate ...
随机推荐
- Angular JS的正确打开姿势——简单实用(下)
前 言 絮叨絮叨 继上篇内容,本篇继续讲一下这款优秀并且实用的前端插件AngularJS. 六. AngularJS中的HTTP 6.1先看看JQuery的Ajax写法 $ajax({ me ...
- 干货,比较全面的c#.net公共帮助类
比较全面的c#帮助类 比较全面的c#帮助类,日常工作收集,包括前面几家公司用到的,各式各样的几乎都能找到,所有功能性代码都是独立的类,类与类之间没有联系,可以单独引用至项目,分享出来,方便大家,几乎都 ...
- HDU1789 Doing Homework again
基础单调队列: #include<cstdio> #include<cstdlib> #include<iostream> #include<algorith ...
- 使用邮件监控Mxnet训练
1. 前言 受到小伙伴的启发,就自己动手写了一个使用邮件监控Mxnet训练的例子.整体不算复杂. 2. 打包训练代码 需要进行监控训练,所以需要将训练的代码打包进一个函数内,通过传参的方式进行训练.还 ...
- Ricequant-米筐金工-估值因子
Ricequant米筐金工--因子分析 作者:戴宇.小湖 上一篇介绍了单因子检验是因子分析前重要的一个步骤,是构建因子库.建立因子模型的基础,这篇报告首先对常见估值因子进行初步的检验. 第一篇.估值因 ...
- IDoc 基础知识
Application Link Enabling ALE主要为了分布式业务系统而设计的.它可以使业务流程中的每个步骤分布在不同的SAP系统上,系统间可以通过IDoc交互数据.IDoc可以认为是个信封 ...
- SAP问题【转载】
1.A:在公司代码分配折旧表时报错? 在公司代码分配折旧表时报错,提示是"3000 的公司代码分录不完全-参见长文本" 希望各位大侠帮我看看. 3000 的公司代码分录不完全-参见 ...
- PHP常用表达式用法
1.匹配正整数:/^[1-9]\d*$/ 2.匹配非负整数(正整数+0):/^\d+$/ 3.匹配中文:/^[\x{4e00}-\x{9fa5}]+$/u 4.匹配Email:/^\w+([-+.]\ ...
- property--staticmethod--classmethod
特性(property): 作为装饰器使用,调用方式从最初的方法调用改变为属性调用 类方法(classmethod):和类进行交互,单不和实例进行交互 在函数中可以不用上传参数 静态方法(static ...
- Java数据结构和算法总结-字符串及高频面试题算法
前言:周末闲来无事,在七月在线上看了看字符串相关算法的讲解视频,收货颇丰,跟着视频讲解简单做了一下笔记,方便以后翻阅复习同时也很乐意分享给大家.什么字符串在算法中有多重要之类的大路边上的客套话就不多说 ...