上篇文章說了,org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator這個類是Spring提供給開發者的AOP的核心類,就是AspectJAwareAdvisorAutoProxyCreator完成了【類/接口-->代理】的轉換過程,首先咱們看一下AspectJAwareAdvisorAutoProxyCreator的層次結構:spring
這裏最值得注意的一點是最左下角的那個方框,我用幾句話總結一下:express
基於以上的分析,將Bean生成代理的時機已經一目瞭然了:在每一個Bean初始化以後,若是須要,調用AspectJAwareAdvisorAutoProxyCreator中的postProcessBeforeInitialization爲Bean生成代理。數組
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { invokeAwareMethods(beanName, bean); return null; } }, getAccessControlContext()); } else { invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
初始化以前是第16行的applyBeanPostProcessorsBeforeInitialization方法,初始化以後即29行的applyBeanPostProcessorsAfterInitialization方法:app
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessAfterInitialization(result, beanName); if (result == null) { return result; } } return result; }
這裏調用每一個BeanPostProcessor的postProcessBeforeInitialization方法。按照以前的分析,看一下AbstractAutoProxyCreator的postProcessAfterInitialization方法實現:函數
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean != null) { Object cacheKey = getCacheKey(bean.getClass(), beanName); if (!this.earlyProxyReferences.contains(cacheKey)) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; }
跟一下第5行的方法wrapIfNecessary:post
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { if (this.targetSourcedBeans.contains(beanName)) { return bean; } if (this.nonAdvisedBeans.contains(cacheKey)) { return bean; } if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.nonAdvisedBeans.add(cacheKey); return bean; } // Create proxy if we have advice. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); if (specificInterceptors != DO_NOT_PROXY) { this.advisedBeans.add(cacheKey); Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } this.nonAdvisedBeans.add(cacheKey); return bean; }
第2行~第11行是一些不須要生成代理的場景判斷,這裏略過。首先咱們要思考的第一個問題是:哪些目標對象須要生成代理?由於配置文件裏面有不少Bean,確定不能對每一個Bean都生成代理,所以須要一套規則判斷Bean是否是須要生成代理,這套規則就是第14行的代碼getAdvicesAndAdvisorsForBean:優化
protected List<Advisor> findEligibleAdvisors(Class beanClass, String beanName) { List<Advisor> candidateAdvisors = findCandidateAdvisors(); List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); extendAdvisors(eligibleAdvisors); if (!eligibleAdvisors.isEmpty()) { eligibleAdvisors = sortAdvisors(eligibleAdvisors); } return eligibleAdvisors; }
顧名思義,方法的意思是爲指定class尋找合適的Advisor。 第2行代碼,尋找候選Advisors,根據上文的配置文件,有兩個候選Advisor,分別是aop:aspect節點下的aop:before和aop:after這兩個,這兩個在XML解析的時候已經被轉換生成了RootBeanDefinition。 跳過第3行的代碼,先看下第4行的代碼extendAdvisors方法,以後再重點看一下第3行的代碼。第4行的代碼extendAdvisors方法做用是向候選Advisor鏈的開頭(也就是List.get(0)的位置)添加一個org.springframework.aop.support.DefaultPointcutAdvisor。 第3行代碼,根據候選Advisors,尋找可使用的Advisor,跟一下方法實現:ui
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) { if (candidateAdvisors.isEmpty()) { return candidateAdvisors; } List<Advisor> eligibleAdvisors = new LinkedList<Advisor>(); for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { eligibleAdvisors.add(candidate); } } boolean hasIntroductions = !eligibleAdvisors.isEmpty(); for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor) { // already processed continue; } if (canApply(candidate, clazz, hasIntroductions)) { eligibleAdvisors.add(candidate); } } return eligibleAdvisors; }
整個方法的主要判斷都圍繞canApply展開方法:this
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) { if (advisor instanceof IntroductionAdvisor) { return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass); } else if (advisor instanceof PointcutAdvisor) { PointcutAdvisor pca = (PointcutAdvisor) advisor; return canApply(pca.getPointcut(), targetClass, hasIntroductions); } else { // It doesn't have a pointcut so we assume it applies. return true; } }
第一個參數advisor的實際類型是AspectJPointcutAdvisor,它是PointcutAdvisor的子類,所以執行第7行的方法:debug
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { if (!pc.getClassFilter().matches(targetClass)) { return false; } MethodMatcher methodMatcher = pc.getMethodMatcher(); IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null; if (methodMatcher instanceof IntroductionAwareMethodMatcher) { introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; } Set<Class> classes = new HashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); classes.add(targetClass); for (Class<?> clazz : classes) { Method[] methods = clazz.getMethods(); for (Method method : methods) { if ((introductionAwareMethodMatcher != null && introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) || methodMatcher.matches(method, targetClass)) { return true; } } } return false; }
這個方法其實就是拿當前Advisor對應的expression作了兩層判斷:
上文分析了爲<bean>生成代理的條件,如今就正式看一下Spring上下文是如何爲<bean>生成代理的。回到AbstractAutoProxyCreator的wrapIfNecessary方法:
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { if (this.targetSourcedBeans.contains(beanName)) { return bean; } if (this.nonAdvisedBeans.contains(cacheKey)) { return bean; } if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.nonAdvisedBeans.add(cacheKey); return bean; } // Create proxy if we have advice. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); if (specificInterceptors != DO_NOT_PROXY) { this.advisedBeans.add(cacheKey); Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } this.nonAdvisedBeans.add(cacheKey); return bean; }
第14行拿到<bean>對應的Advisor數組,第15行判斷只要Advisor數組不爲空,那麼就會經過第17行的代碼爲<bean>建立代理:
protected Object createProxy( Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) { ProxyFactory proxyFactory = new ProxyFactory(); // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig. proxyFactory.copyFrom(this); if (!shouldProxyTargetClass(beanClass, beanName)) { // Must allow for introductions; can't just set interfaces to // the target's interfaces only. Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader); for (Class<?> targetInterface : targetInterfaces) { proxyFactory.addInterface(targetInterface); } } Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); for (Advisor advisor : advisors) { proxyFactory.addAdvisor(advisor); } proxyFactory.setTargetSource(targetSource); customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(this.freezeProxy); if (advisorsPreFiltered()) { proxyFactory.setPreFiltered(true); } return proxyFactory.getProxy(this.proxyClassLoader); }
第4行~第6行new出了一個ProxyFactory,Proxy,顧名思義,代理工廠的意思,提供了簡單的方式使用代碼獲取和配置AOP代理。
第8行的代碼作了一個判斷,判斷的內容是aop:config這個節點中proxy-target-class="false"或者proxy-target-class不配置,即不使用CGLIB生成代理。若是知足條件,進判斷,獲取當前Bean實現的全部接口,講這些接口Class對象都添加到ProxyFactory中。
第17行~第28行的代碼沒什麼看的必要,向ProxyFactory中添加一些參數而已。重點看第30行proxyFactory.getProxy(this.proxyClassLoader)這句:
public Object getProxy(ClassLoader classLoader) { return createAopProxy().getProxy(classLoader); }
實現代碼就一行,可是卻明確告訴咱們作了兩件事情:
看一下createAopProxy()方法的實現,它位於DefaultAopProxyFactory類中:
protected final synchronized AopProxy createAopProxy() { if (!this.active) { activate(); } return getAopProxyFactory().createAopProxy(this); }
前面的部分沒什麼必要看,直接進入重點即createAopProxy方法:
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) { Class targetClass = config.getTargetClass(); if (targetClass == null) { throw new AopConfigException("TargetSource cannot determine target class: " + "Either an interface or a target is required for proxy creation."); } if (targetClass.isInterface()) { return new JdkDynamicAopProxy(config); } if (!cglibAvailable) { throw new AopConfigException( "Cannot proxy target class because CGLIB2 is not available. " + "Add CGLIB to the class path or specify proxy interfaces."); } return CglibProxyFactory.createCglibProxy(config); } else { return new JdkDynamicAopProxy(config); } }
平時咱們說AOP原理三句話就能歸納:
對類生成代理使用CGLIB
對接口生成代理使用JDK原生的Proxy
能夠經過配置文件指定對接口使用CGLIB生成代理 這三句話的出處就是createAopProxy方法。看到默認是第19行的代碼使用JDK自帶的Proxy生成代理,碰到如下三種狀況例外:
ProxyConfig的isOptimize方法爲true,這表示讓Spring本身去優化而不是用戶指定
ProxyConfig的isProxyTargetClass方法爲true,這表示配置了proxy-target-class="true"
ProxyConfig知足hasNoUserSuppliedProxyInterfaces方法執行結果爲true,這表示<bean>對象沒有實現任何接口或者實現的接口是SpringProxy接口
在進入第2行的if判斷以後再根據目標<bean>的類型決定返回哪一種AopProxy。簡單總結起來就是:
固然,不論是JdkDynamicAopProxy仍是Cglib2AopProxy,AdvisedSupport都是做爲構造函數參數傳入的,裏面存儲了具體的Advisor。
其實代碼已經分析到了JdkDynamicAopProxy和Cglib2AopProxy,剩下的就沒什麼好講的了,無非就是看對這兩種方式生成代理的熟悉程度而已。
Cglib2AopProxy生成代理的代碼就不看了,對Cglib不熟悉的朋友能夠看Cglib及其基本使用一文。
JdkDynamicAopProxy生成代理的方式稍微看一下:
public Object getProxy(ClassLoader classLoader) { if (logger.isDebugEnabled()) { logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource()); } Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised); findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); }
這邊解釋一下第5行和第6行的代碼,第5行代碼的做用是拿到全部要代理的接口,第6行代碼的做用是嘗試尋找這些接口方法裏面有沒有equals方法和hashCode方法,同時都有的話打個標記,尋找結束,equals方法和hashCode方法有特殊處理。
最終經過第7行的Proxy.newProxyInstance方法獲取接口/類對應的代理對象,Proxy是JDK原生支持的生成代理的方式。
前面已經詳細分析了爲接口/類生成代理的原理,生成代理以後就要調用方法了,這裏看一下使用JdkDynamicAopProxy調用方法的原理。
因爲JdkDynamicAopProxy自己實現了InvocationHandler接口,所以具體代理先後處理的邏輯在invoke方法中:
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. 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. retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args); } 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. retVal = invocation.proceed(); } // Massage return value if necessary. if (retVal != null && retVal == target && method.getReturnType().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; } return retVal; } finally { if (target != null && !targetSource.isStatic()) { // Must have come from TargetSource. targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } }
第11行~第18行的代碼,表示equals方法與hashCode方法即便知足expression規則,也不會爲之產生代理內容,調用的是JdkDynamicAopProxy的equals方法與hashCode方法。至於這兩個方法是什麼做用,能夠本身查看一下源代碼。
第19行~第23行的代碼,表示方法所屬的Class是一個接口而且方法所屬的Class是AdvisedSupport的父類或者父接口,直接經過反射調用該方法。
第27行~第30行的代碼,是用於判斷是否將代理暴露出去的,由aop:config標籤中的expose-proxy="true/false"配置。
第41行的代碼,獲取AdvisedSupport中的全部攔截器和動態攔截器列表,用於攔截方法,具體到咱們的實際代碼,列表中有三個Object,分別是:
第51行~第56行的代碼,若是攔截器列表不爲空,按照註釋的意思,須要一個ReflectiveMethodInvocation,並經過proceed方法對原方法進行攔截,proceed方法感興趣的朋友能夠去看一下,裏面使用到了遞歸的思想對chain中的Object進行了層層的調用。