public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)throws Throwable { Object oldProxy = null; boolean setProxyContext = false; Object target = null; TargetSource targetSource = this.advised.getTargetSource(); try { 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); Object retVal; // Check whether we only have one InvokerInterceptor: that is, // no real advice, but just reflective invocation of the target. if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) { Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); retVal = methodProxy.invoke(target, argsToUse); } else { // 创建CglibMethodInvocation类,并执行processd()方法 // CglibMethodInvocation类实际上是一个调用链对象,也就是说这里将目标类、代理对象、代理方法、调用参数、以及最关键的增强列表<chain> // 记录到这个对象中,还包含了当前索引下标等等信息。也就是调用它的process()方法之后,它就会遍历这个增强列表,执行每一个增强。 retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed(); } retVal = processReturnType(proxy, target, method, retVal); return retVal; }finally { if (target != null && !targetSource.isStatic()) { targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } }
publicstaticbooleanmakeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors){ // 对获取到的增强列表进行遍历,这里来了一个二次核查,如果存在aop的增强,则在列表下标为0的位置,添加 // ExposeInvocationInterceptor类。 if (!advisors.isEmpty()) { boolean foundAspectJAdvice = false; for (Advisor advisor : advisors) { // Be careful not to get the Advice without a guard, as this might eagerly // instantiate a non-singleton AspectJ aspect... if (isAspectJAdvice(advisor)) { foundAspectJAdvice = true; break; } } if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) { advisors.add(0, ExposeInvocationInterceptor.ADVISOR); returntrue; } } returnfalse; }