Spring源码分析:AOP源码解析(下篇)

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

AspectJAwareAdvisorAutoProxyCreator及为Bean生成代理时机分析

上篇文章说了,org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator这个类是Spring提供给开发者的AOP的核心类,就是AspectJAwareAdvisorAutoProxyCreator完成了【类/接口–>代理】的转换过程,首先我们看一下AspectJAwareAdvisorAutoProxyCreator的层次结构:

20191102100640\_1.png

这里最值得注意的一点是最左下角的那个方框,我用几句话总结一下:

  1. AspectJAwareAdvisorAutoProxyCreator是BeanPostProcessor接口的实现类
  2. postProcessBeforeInitialization方法与postProcessAfterInitialization方法实现在父类AbstractAutoProxyCreator中
  3. postProcessBeforeInitialization方法是一个空实现
  4. 逻辑代码在postProcessAfterInitialization方法中

基于以上的分析,将Bean生成代理的时机已经一目了然了:在每个Bean初始化之后,如果需要,调用AspectJAwareAdvisorAutoProxyCreator中的postProcessBeforeInitialization为Bean生成代理。

代理对象实例化—-判断是否为生成代理

上文分析了Bean生成代理的时机是在每个Bean初始化之后,下面把代码定位到Bean初始化之后,先是AbstractAutowireCapableBeanFactory的initializeBean方法进行初始化:

1234567891011121314151617181920212223242526272829303132 protectedObjectinitializeBean(finalStringbeanName,finalObjectbean,RootBeanDefinitionmbd){   if(System.getSecurityManager()!=null){       AccessController.doPrivileged(newPrivilegedAction<Object>(){           publicObjectrun(){               invokeAwareMethods(beanName,bean);               returnnull;           }       },getAccessControlContext());   }   else{       invokeAwareMethods(beanName,bean);   }   ObjectwrappedBean=bean;   if(mbd==null !mbd.isSynthetic()){       wrappedBean=applyBeanPostProcessorsBeforeInitialization(wrappedBean,beanName);   }   try{   invokeInitMethods(beanName,wrappedBean,mbd);   }   catch(Throwableex){       thrownewBeanCreationException(               (mbd!=null?mbd.getResourceDescription():null),               beanName,"Invocationofinitmethodfailed",ex);   }   if(mbd==null !mbd.isSynthetic()){       wrappedBean=applyBeanPostProcessorsAfterInitialization(wrappedBean,beanName);   }   returnwrappedBean;}
1234567891011121314151617181920212223242526272829303132 protectedObjectinitializeBean(finalStringbeanName,finalObjectbean,RootBeanDefinitionmbd){   if(System.getSecurityManager()!=null){       AccessController.doPrivileged(newPrivilegedAction<Object>(){           publicObjectrun(){               invokeAwareMethods(beanName,bean);               returnnull;           }       },getAccessControlContext());   }   else{       invokeAwareMethods(beanName,bean);   }   ObjectwrappedBean=bean;   if(mbd==null !mbd.isSynthetic()){       wrappedBean=applyBeanPostProcessorsBeforeInitialization(wrappedBean,beanName);   }   try{   invokeInitMethods(beanName,wrappedBean,mbd);   }   catch(Throwableex){       thrownewBeanCreationException(               (mbd!=null?mbd.getResourceDescription():null),               beanName,"Invocationofinitmethodfailed",ex);   }   if(mbd==null !mbd.isSynthetic()){       wrappedBean=applyBeanPostProcessorsAfterInitialization(wrappedBean,beanName);   }   returnwrappedBean;}

初始化之前是第16行的applyBeanPostProcessorsBeforeInitialization方法,初始化之后即29行的applyBeanPostProcessorsAfterInitialization方法:

123456789101112 publicObjectapplyBeanPostProcessorsAfterInitialization(ObjectexistingBean,StringbeanName)       throwsBeansException{   Objectresult=existingBean;   for(BeanPostProcessorbeanProcessor:getBeanPostProcessors()){       result=beanProcessor.postProcessAfterInitialization(result,beanName);       if(result==null){           returnresult;       }   }   returnresult;}
123456789101112 publicObjectapplyBeanPostProcessorsAfterInitialization(ObjectexistingBean,StringbeanName)       throwsBeansException{   Objectresult=existingBean;   for(BeanPostProcessorbeanProcessor:getBeanPostProcessors()){       result=beanProcessor.postProcessAfterInitialization(result,beanName);       if(result==null){           returnresult;       }   }   returnresult;}

这里调用每个BeanPostProcessor的postProcessBeforeInitialization方法。按照之前的分析,看一下AbstractAutoProxyCreator的postProcessAfterInitialization方法实现:

123456789 publicObjectpostProcessAfterInitialization(Objectbean,StringbeanName)throwsBeansException{   if(bean!=null){       ObjectcacheKey=getCacheKey(bean.getClass(),beanName);       if(!this.earlyProxyReferences.contains(cacheKey)){           returnwrapIfNecessary(bean,beanName,cacheKey);       }   }   returnbean;}
123456789 publicObjectpostProcessAfterInitialization(Objectbean,StringbeanName)throwsBeansException{   if(bean!=null){       ObjectcacheKey=getCacheKey(bean.getClass(),beanName);       if(!this.earlyProxyReferences.contains(cacheKey)){           returnwrapIfNecessary(bean,beanName,cacheKey);       }   }   returnbean;}

跟一下第5行的方法wrapIfNecessary:

123456789101112131415161718192021222324 protectedObjectwrapIfNecessary(Objectbean,StringbeanName,ObjectcacheKey){   if(this.targetSourcedBeans.contains(beanName)){       returnbean;   }   if(this.nonAdvisedBeans.contains(cacheKey)){       returnbean;   }   if(isInfrastructureClass(bean.getClass()) shouldSkip(bean.getClass(),beanName)){       this.nonAdvisedBeans.add(cacheKey);       returnbean;   }   //Createproxyifwehaveadvice.   Object[]specificInterceptors=getAdvicesAndAdvisorsForBean(bean.getClass(),beanName,null);   if(specificInterceptors!=DO_NOT_PROXY){       this.advisedBeans.add(cacheKey);       Objectproxy=createProxy(bean.getClass(),beanName,specificInterceptors,newSingletonTargetSource(bean));       this.proxyTypes.put(cacheKey,proxy.getClass());       returnproxy;   }   this.nonAdvisedBeans.add(cacheKey);   returnbean;}
123456789101112131415161718192021222324 protectedObjectwrapIfNecessary(Objectbean,StringbeanName,ObjectcacheKey){   if(this.targetSourcedBeans.contains(beanName)){       returnbean;   }   if(this.nonAdvisedBeans.contains(cacheKey)){       returnbean;   }   if(isInfrastructureClass(bean.getClass()) shouldSkip(bean.getClass(),beanName)){       this.nonAdvisedBeans.add(cacheKey);       returnbean;   }   //Createproxyifwehaveadvice.   Object[]specificInterceptors=getAdvicesAndAdvisorsForBean(bean.getClass(),beanName,null);   if(specificInterceptors!=DO_NOT_PROXY){       this.advisedBeans.add(cacheKey);       Objectproxy=createProxy(bean.getClass(),beanName,specificInterceptors,newSingletonTargetSource(bean));       this.proxyTypes.put(cacheKey,proxy.getClass());       returnproxy;   }   this.nonAdvisedBeans.add(cacheKey);   returnbean;}

第2行~第11行是一些不需要生成代理的场景判断,这里略过。首先我们要思考的第一个问题是:哪些目标对象需要生成代理?因为配置文件里面有很多Bean,肯定不能对每个Bean都生成代理,因此需要一套规则判断Bean是不是需要生成代理,这套规则就是第14行的代码getAdvicesAndAdvisorsForBean:

123456789 protectedList<Advisor>findEligibleAdvisors(ClassbeanClass,StringbeanName){   List<Advisor>candidateAdvisors=findCandidateAdvisors();   List<Advisor>eligibleAdvisors=findAdvisorsThatCanApply(candidateAdvisors,beanClass,beanName);   extendAdvisors(eligibleAdvisors);   if(!eligibleAdvisors.isEmpty()){       eligibleAdvisors=sortAdvisors(eligibleAdvisors);   }   returneligibleAdvisors;}
123456789 protectedList<Advisor>findEligibleAdvisors(ClassbeanClass,StringbeanName){   List<Advisor>candidateAdvisors=findCandidateAdvisors();   List<Advisor>eligibleAdvisors=findAdvisorsThatCanApply(candidateAdvisors,beanClass,beanName);   extendAdvisors(eligibleAdvisors);   if(!eligibleAdvisors.isEmpty()){       eligibleAdvisors=sortAdvisors(eligibleAdvisors);   }   returneligibleAdvisors;}

顾名思义,方法的意思是为指定class寻找合适的Advisor。

第2行代码,寻找候选Advisors,根据上文的配置文件,有两个候选Advisor,分别是节点下的这两个,这两个在XML解析的时候已经被转换生成了RootBeanDefinition。

跳过第3行的代码,先看下第4行的代码extendAdvisors方法,之后再重点看一下第3行的代码。第4行的代码extendAdvisors方法作用是向候选Advisor链的开头(也就是List.get(0)的位置)添加一个org.springframework.aop.support.DefaultPointcutAdvisor。

第3行代码,根据候选Advisors,寻找可以使用的Advisor,跟一下方法实现:

12345678910111213141516171819202122 publicstaticList<Advisor>findAdvisorsThatCanApply(List<Advisor>candidateAdvisors,Class<?>clazz){   if(candidateAdvisors.isEmpty()){       returncandidateAdvisors;   }   List<Advisor>eligibleAdvisors=newLinkedList<Advisor>();   for(Advisorcandidate:candidateAdvisors){       if(candidateinstanceofIntroductionAdvisor&&canApply(candidate,clazz)){           eligibleAdvisors.add(candidate);       }   }   booleanhasIntroductions=!eligibleAdvisors.isEmpty();   for(Advisorcandidate:candidateAdvisors){       if(candidateinstanceofIntroductionAdvisor){           //alreadyprocessed           continue;       }       if(canApply(candidate,clazz,hasIntroductions)){           eligibleAdvisors.add(candidate);       }   }   returneligibleAdvisors;}
12345678910111213141516171819202122 publicstaticList<Advisor>findAdvisorsThatCanApply(List<Advisor>candidateAdvisors,Class<?>clazz){   if(candidateAdvisors.isEmpty()){       returncandidateAdvisors;   }   List<Advisor>eligibleAdvisors=newLinkedList<Advisor>();   for(Advisorcandidate:candidateAdvisors){       if(candidateinstanceofIntroductionAdvisor&&canApply(candidate,clazz)){           eligibleAdvisors.add(candidate);       }   }   booleanhasIntroductions=!eligibleAdvisors.isEmpty();   for(Advisorcandidate:candidateAdvisors){       if(candidateinstanceofIntroductionAdvisor){           //alreadyprocessed           continue;       }       if(canApply(candidate,clazz,hasIntroductions)){           eligibleAdvisors.add(candidate);       }   }   returneligibleAdvisors;}

整个方法的主要判断都围绕canApply展开方法:

12345678910111213 publicstaticbooleancanApply(Advisoradvisor,Class<?>targetClass,booleanhasIntroductions){   if(advisorinstanceofIntroductionAdvisor){       return((IntroductionAdvisor)advisor).getClassFilter().matches(targetClass);   }   elseif(advisorinstanceofPointcutAdvisor){       PointcutAdvisorpca=(PointcutAdvisor)advisor;       returncanApply(pca.getPointcut(),targetClass,hasIntroductions);   }   else{       //Itdoesn'thaveapointcutsoweassumeitapplies.       returntrue;   }}
12345678910111213 publicstaticbooleancanApply(Advisoradvisor,Class<?>targetClass,booleanhasIntroductions){   if(advisorinstanceofIntroductionAdvisor){       return((IntroductionAdvisor)advisor).getClassFilter().matches(targetClass);   }   elseif(advisorinstanceofPointcutAdvisor){       PointcutAdvisorpca=(PointcutAdvisor)advisor;       returncanApply(pca.getPointcut(),targetClass,hasIntroductions);   }   else{       //Itdoesn'thaveapointcutsoweassumeitapplies.       returntrue;   }}

第一个参数advisor的实际类型是AspectJPointcutAdvisor,它是PointcutAdvisor的子类,因此执行第7行的方法:

12345678910111213141516171819202122232425 publicstaticbooleancanApply(Pointcutpc,Class<?>targetClass,booleanhasIntroductions){   if(!pc.getClassFilter().matches(targetClass)){       returnfalse;   }   MethodMatchermethodMatcher=pc.getMethodMatcher();   IntroductionAwareMethodMatcherintroductionAwareMethodMatcher=null;   if(methodMatcherinstanceofIntroductionAwareMethodMatcher){       introductionAwareMethodMatcher=(IntroductionAwareMethodMatcher)methodMatcher;   }   Set<Class>classes=newHashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));   classes.add(targetClass);   for(Class<?>clazz:classes){       Method[]methods=clazz.getMethods();       for(Methodmethod:methods){           if((introductionAwareMethodMatcher!=null&&               introductionAwareMethodMatcher.matches(method,targetClass,hasIntroductions))                    methodMatcher.matches(method,targetClass)){               returntrue;           }       }   }   returnfalse;}
12345678910111213141516171819202122232425 publicstaticbooleancanApply(Pointcutpc,Class<?>targetClass,booleanhasIntroductions){   if(!pc.getClassFilter().matches(targetClass)){       returnfalse;   }   MethodMatchermethodMatcher=pc.getMethodMatcher();   IntroductionAwareMethodMatcherintroductionAwareMethodMatcher=null;   if(methodMatcherinstanceofIntroductionAwareMethodMatcher){       introductionAwareMethodMatcher=(IntroductionAwareMethodMatcher)methodMatcher;   }   Set<Class>classes=newHashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));   classes.add(targetClass);   for(Class<?>clazz:classes){       Method[]methods=clazz.getMethods();       for(Methodmethod:methods){           if((introductionAwareMethodMatcher!=null&&               introductionAwareMethodMatcher.matches(method,targetClass,hasIntroductions))                    methodMatcher.matches(method,targetClass)){               returntrue;           }       }   }   returnfalse;}

这个方法其实就是拿当前Advisor对应的expression做了两层判断:

  1. 目标类必须满足expression的匹配规则
  2. 目标类中的方法必须满足expression的匹配规则,当然这里方法不是全部需要满足expression的匹配规则,有一个方法满足即可

如果以上两条都满足,那么容器则会判断该满足条件,需要被生成代理对象,具体方式为返回一个数组对象,该数组对象中存储的是对应的Advisor。

代理对象实例化—-为生成代理代码上下文梳理

上文分析了为生成代理的条件,现在就正式看一下Spring上下文是如何为生成代理的。回到AbstractAutoProxyCreator的wrapIfNecessary方法:

123456789101112131415161718192021222324 protectedObjectwrapIfNecessary(Objectbean,StringbeanName,ObjectcacheKey){   if(this.targetSourcedBeans.contains(beanName)){       returnbean;   }   if(this.nonAdvisedBeans.contains(cacheKey)){       returnbean;   }   if(isInfrastructureClass(bean.getClass()) shouldSkip(bean.getClass(),beanName)){       this.nonAdvisedBeans.add(cacheKey);       returnbean;   }   //Createproxyifwehaveadvice.   Object[]specificInterceptors=getAdvicesAndAdvisorsForBean(bean.getClass(),beanName,null);   if(specificInterceptors!=DO_NOT_PROXY){       this.advisedBeans.add(cacheKey);       Objectproxy=createProxy(bean.getClass(),beanName,specificInterceptors,newSingletonTargetSource(bean));       this.proxyTypes.put(cacheKey,proxy.getClass());       returnproxy;   }   this.nonAdvisedBeans.add(cacheKey);   returnbean;}
123456789101112131415161718192021222324 protectedObjectwrapIfNecessary(Objectbean,StringbeanName,ObjectcacheKey){   if(this.targetSourcedBeans.contains(beanName)){       returnbean;   }   if(this.nonAdvisedBeans.contains(cacheKey)){       returnbean;   }   if(isInfrastructureClass(bean.getClass()) shouldSkip(bean.getClass(),beanName)){       this.nonAdvisedBeans.add(cacheKey);       returnbean;   }   //Createproxyifwehaveadvice.   Object[]specificInterceptors=getAdvicesAndAdvisorsForBean(bean.getClass(),beanName,null);   if(specificInterceptors!=DO_NOT_PROXY){       this.advisedBeans.add(cacheKey);       Objectproxy=createProxy(bean.getClass(),beanName,specificInterceptors,newSingletonTargetSource(bean));       this.proxyTypes.put(cacheKey,proxy.getClass());       returnproxy;   }   this.nonAdvisedBeans.add(cacheKey);   returnbean;}

第14行拿到对应的Advisor数组,第15行判断只要Advisor数组不为空,那么就会通过第17行的代码为创建代理:

12345678910111213141516171819202122232425262728293031 protectedObjectcreateProxy(       Class<?>beanClass,StringbeanName,Object[]specificInterceptors,TargetSourcetargetSource){   ProxyFactoryproxyFactory=newProxyFactory();   //Copyourproperties(proxyTargetClassetc)inheritedfromProxyConfig.   proxyFactory.copyFrom(this);   if(!shouldProxyTargetClass(beanClass,beanName)){       //Mustallowforintroductions;can'tjustsetinterfacesto       //thetarget'sinterfacesonly.       Class<?>[]targetInterfaces=ClassUtils.getAllInterfacesForClass(beanClass,this.proxyClassLoader);       for(Class<?>targetInterface:targetInterfaces){           proxyFactory.addInterface(targetInterface);       }   }   Advisor[]advisors=buildAdvisors(beanName,specificInterceptors);   for(Advisoradvisor:advisors){       proxyFactory.addAdvisor(advisor);   }   proxyFactory.setTargetSource(targetSource);   customizeProxyFactory(proxyFactory);   proxyFactory.setFrozen(this.freezeProxy);   if(advisorsPreFiltered()){       proxyFactory.setPreFiltered(true);   }   returnproxyFactory.getProxy(this.proxyClassLoader);}
12345678910111213141516171819202122232425262728293031 protectedObjectcreateProxy(       Class<?>beanClass,StringbeanName,Object[]specificInterceptors,TargetSourcetargetSource){   ProxyFactoryproxyFactory=newProxyFactory();   //Copyourproperties(proxyTargetClassetc)inheritedfromProxyConfig.   proxyFactory.copyFrom(this);   if(!shouldProxyTargetClass(beanClass,beanName)){       //Mustallowforintroductions;can'tjustsetinterfacesto       //thetarget'sinterfacesonly.       Class<?>[]targetInterfaces=ClassUtils.getAllInterfacesForClass(beanClass,this.proxyClassLoader);       for(Class<?>targetInterface:targetInterfaces){           proxyFactory.addInterface(targetInterface);       }   }   Advisor[]advisors=buildAdvisors(beanName,specificInterceptors);   for(Advisoradvisor:advisors){       proxyFactory.addAdvisor(advisor);   }   proxyFactory.setTargetSource(targetSource);   customizeProxyFactory(proxyFactory);   proxyFactory.setFrozen(this.freezeProxy);   if(advisorsPreFiltered()){       proxyFactory.setPreFiltered(true);   }   returnproxyFactory.getProxy(this.proxyClassLoader);}

第4行~第6行new出了一个ProxyFactory,Proxy,顾名思义,代理工厂的意思,提供了简单的方式使用代码获取和配置AOP代理。

第8行的代码做了一个判断,判断的内容是这个节点中proxy-target-class=”false”或者proxy-target-class不配置,即不使用CGLIB生成代理。如果满足条件,进判断,获取当前Bean实现的所有接口,讲这些接口Class对象都添加到ProxyFactory中。

第17行~第28行的代码没什么看的必要,向ProxyFactory中添加一些参数而已。重点看第30行proxyFactory.getProxy(this.proxyClassLoader)这句:

123 publicObjectgetProxy(ClassLoaderclassLoader){returncreateAopProxy().getProxy(classLoader);}
123 publicObjectgetProxy(ClassLoaderclassLoader){returncreateAopProxy().getProxy(classLoader);}

实现代码就一行,但是却明确告诉我们做了两件事情:

  1. 创建AopProxy接口实现类
  2. 通过AopProxy接口的实现类的getProxy方法获取对应的代理

就从这两个点出发,分两部分分析一下。

代理对象实例化—-创建AopProxy接口实现类

看一下createAopProxy()方法的实现,它位于DefaultAopProxyFactory类中:

123456 protectedfinalsynchronizedAopProxycreateAopProxy(){if(!this.active){activate();}returngetAopProxyFactory().createAopProxy(this);}
123456 protectedfinalsynchronizedAopProxycreateAopProxy(){if(!this.active){activate();}returngetAopProxyFactory().createAopProxy(this);}

前面的部分没什么必要看,直接进入重点即createAopProxy方法:

123456789101112131415161718192021 publicAopProxycreateAopProxy(AdvisedSupportconfig)throwsAopConfigException{   if(config.isOptimize() config.isProxyTargetClass() hasNoUserSuppliedProxyInterfaces(config)){       ClasstargetClass=config.getTargetClass();       if(targetClass==null){           thrownewAopConfigException("TargetSourcecannotdeterminetargetclass:"+                   "Eitheraninterfaceoratargetisrequiredforproxycreation.");       }       if(targetClass.isInterface()){           returnnewJdkDynamicAopProxy(config);       }       if(!cglibAvailable){           thrownewAopConfigException(                   "CannotproxytargetclassbecauseCGLIB2isnotavailable."+                   "AddCGLIBtotheclasspathorspecifyproxyinterfaces.");       }       returnCglibProxyFactory.createCglibProxy(config);   }   else{       returnnewJdkDynamicAopProxy(config);   }}
123456789101112131415161718192021 publicAopProxycreateAopProxy(AdvisedSupportconfig)throwsAopConfigException{   if(config.isOptimize() config.isProxyTargetClass() hasNoUserSuppliedProxyInterfaces(config)){       ClasstargetClass=config.getTargetClass();       if(targetClass==null){           thrownewAopConfigException("TargetSourcecannotdeterminetargetclass:"+                   "Eitheraninterfaceoratargetisrequiredforproxycreation.");       }       if(targetClass.isInterface()){           returnnewJdkDynamicAopProxy(config);       }       if(!cglibAvailable){           thrownewAopConfigException(                   "CannotproxytargetclassbecauseCGLIB2isnotavailable."+                   "AddCGLIBtotheclasspathorspecifyproxyinterfaces.");       }       returnCglibProxyFactory.createCglibProxy(config);   }   else{       returnnewJdkDynamicAopProxy(config);   }}

平时我们说AOP原理三句话就能概括:

  1. 对类生成代理使用CGLIB
  2. 对接口生成代理使用JDK原生的Proxy
  3. 可以通过配置文件指定对接口使用CGLIB生成代理

这三句话的出处就是createAopProxy方法。看到默认是第19行的代码使用JDK自带的Proxy生成代理,碰到以下三种情况例外:

  1. ProxyConfig的isOptimize方法为true,这表示让Spring自己去优化而不是用户指定
  2. ProxyConfig的isProxyTargetClass方法为true,这表示配置了proxy-target-class=”true”
  3. ProxyConfig满足hasNoUserSuppliedProxyInterfaces方法执行结果为true,这表示对象没有实现任何接口或者实现的接口是SpringProxy接口

在进入第2行的if判断之后再根据目标的类型决定返回哪种AopProxy。简单总结起来就是:

  1. proxy-target-class没有配置或者proxy-target-class=”false”,返回JdkDynamicAopProxy
  2. proxy-target-class=”true”或者对象没有实现任何接口或者只实现了SpringProxy接口,返回Cglib2AopProxy

当然,不管是JdkDynamicAopProxy还是Cglib2AopProxy,AdvisedSupport都是作为构造函数参数传入的,里面存储了具体的Advisor。

代理对象实例化—-通过getProxy方法获取对应的代理

其实代码已经分析到了JdkDynamicAopProxy和Cglib2AopProxy,剩下的就没什么好讲的了,无非就是看对这两种方式生成代理的熟悉程度而已。

Cglib2AopProxy生成代理的代码就不看了,对Cglib不熟悉的朋友可以看Cglib及其基本使用一文。

JdkDynamicAopProxy生成代理的方式稍微看一下:

12345678 publicObjectgetProxy(ClassLoaderclassLoader){   if(logger.isDebugEnabled()){       logger.debug("CreatingJDKdynamicproxy:targetsourceis"+this.advised.getTargetSource());   }   Class[]proxiedInterfaces=AopProxyUtils.completeProxiedInterfaces(this.advised);   findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);   returnProxy.newProxyInstance(classLoader,proxiedInterfaces,this);}
12345678 publicObjectgetProxy(ClassLoaderclassLoader){   if(logger.isDebugEnabled()){       logger.debug("CreatingJDKdynamicproxy:targetsourceis"+this.advised.getTargetSource());   }   Class[]proxiedInterfaces=AopProxyUtils.completeProxiedInterfaces(this.advised);   findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);   returnProxy.newProxyInstance(classLoader,proxiedInterfaces,this);}

这边解释一下第5行和第6行的代码,第5行代码的作用是拿到所有要代理的接口,第6行代码的作用是尝试寻找这些接口方法里面有没有equals方法和hashCode方法,同时都有的话打个标记,寻找结束,equals方法和hashCode方法有特殊处理。

最终通过第7行的Proxy.newProxyInstance方法获取接口/类对应的代理对象,Proxy是JDK原生支持的生成代理的方式。

代理方法调用原理

前面已经详细分析了为接口/类生成代理的原理,生成代理之后就要调用方法了,这里看一下使用JdkDynamicAopProxy调用方法的原理。

由于JdkDynamicAopProxy本身实现了InvocationHandler接口,因此具体代理前后处理的逻辑在invoke方法中:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{   MethodInvocationinvocation;   ObjectoldProxy=null;   booleansetProxyContext=false;   TargetSourcetargetSource=this.advised.targetSource;   ClasstargetClass=null;   Objecttarget=null;   try{       if(!this.equalsDefined&&AopUtils.isEqualsMethod(method)){           //Thetargetdoesnotimplementtheequals(Object)methoditself.           returnequals(args[0]);       }       if(!this.hashCodeDefined&&AopUtils.isHashCodeMethod(method)){           //ThetargetdoesnotimplementthehashCode()methoditself.           returnhashCode();       }       if(!this.advised.opaque&&method.getDeclaringClass().isInterface()&&               method.getDeclaringClass().isAssignableFrom(Advised.class)){           //ServiceinvocationsonProxyConfigwiththeproxyconfig...           returnAopUtils.invokeJoinpointUsingReflection(this.advised,method,args);       }       ObjectretVal;       if(this.advised.exposeProxy){           //Makeinvocationavailableifnecessary.           oldProxy=AopContext.setCurrentProxy(proxy);           setProxyContext=true;       }       //Maybenull.Getaslateaspossibletominimizethetimewe"own"thetarget,       //incaseitcomesfromapool.       target=targetSource.getTarget();       if(target!=null){           targetClass=target.getClass();       }       //Gettheinterceptionchainforthismethod.       List<Object>chain=this.advised.getInterceptorsAndDynamicInterceptionAdvice(method,targetClass);       //Checkwhetherwehaveanyadvice.Ifwedon't,wecanfallbackondirect       //reflectiveinvocationofthetarget,andavoidcreatingaMethodInvocation.       if(chain.isEmpty()){           //WecanskipcreatingaMethodInvocation:justinvokethetargetdirectly           //NotethatthefinalinvokermustbeanInvokerInterceptorsoweknowitdoes           //nothingbutareflectiveoperationonthetarget,andnohotswappingorfancyproxying.           retVal=AopUtils.invokeJoinpointUsingReflection(target,method,args);       }       else{           //Weneedtocreateamethodinvocation...           invocation=newReflectiveMethodInvocation(proxy,target,method,args,targetClass,chain);           //Proceedtothejoinpointthroughtheinterceptorchain.           retVal=invocation.proceed();       }       //Massagereturnvalueifnecessary.       if(retVal!=null&&retVal==target&&method.getReturnType().isInstance(proxy)&&               !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())){           //Specialcase:itreturned"this"andthereturntypeofthemethod           //istype-compatible.Notethatwecan'thelpifthetargetsets           //areferencetoitselfinanotherreturnedobject.           retVal=proxy;       }       returnretVal;   }   finally{       if(target!=null&&!targetSource.isStatic()){           //MusthavecomefromTargetSource.           targetSource.releaseTarget(target);       }       if(setProxyContext){           //Restoreoldproxy.           AopContext.setCurrentProxy(oldProxy);       }   }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778

第11行~第18行的代码,表示equals方法与hashCode方法即使满足expression规则,也不会为之产生代理内容,调用的是JdkDynamicAopProxy的equals方法与hashCode方法。至于这两个方法是什么作用,可以自己查看一下源代码。

第19行~第23行的代码,表示方法所属的Class是一个接口并且方法所属的Class是AdvisedSupport的父类或者父接口,直接通过反射调用该方法。

第27行~第30行的代码,是用于判断是否将代理暴露出去的,由标签中的expose-proxy=”true/false”配置。

第41行的代码,获取AdvisedSupport中的所有拦截器和动态拦截器列表,用于拦截方法,具体到我们的实际代码,列表中有三个Object,分别是:

  • chain.get(0):ExposeInvocationInterceptor,这是一个默认的拦截器,对应的原Advisor为DefaultPointcutAdvisor
  • chain.get(1):MethodBeforeAdviceInterceptor,用于在实际方法调用之前的拦截,对应的原Advisor为AspectJMethodBeforeAdvice
  • chain.get(2):AspectJAfterAdvice,用于在实际方法调用之后的处理

第45行~第50行的代码,如果拦截器列表为空,很正常,因为某个类/接口下的某个方法可能不满足expression的匹配规则,因此此时通过反射直接调用该方法。

第51行~第56行的代码,如果拦截器列表不为空,按照注释的意思,需要一个ReflectiveMethodInvocation,并通过proceed方法对原方法进行拦截,proceed方法感兴趣的朋友可以去看一下,里面使用到了递归的思想对chain中的Object进行了层层的调用


来源:http://ddrv.cn

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » Spring源码分析:AOP源码解析(下篇)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏