@OverridepublicvoidaddAdvice(intpos,Adviceadvice)throwsAopConfigException{Assert.notNull(advice,"Advice must not be null");if(adviceinstanceofIntroductionInfo){// We don't need an IntroductionAdvisor for this kind of introduction:// It's fully self-describing.addAdvisor(pos,newDefaultIntroductionAdvisor(advice,(IntroductionInfo)advice));}elseif(adviceinstanceofDynamicIntroductionAdvice){// We need an IntroductionAdvisor for this kind of introduction.thrownewAopConfigException("DynamicIntroductionAdvice may only be added as part of IntroductionAdvisor");}else{addAdvisor(pos,newDefaultPointcutAdvisor(advice));}}
@OverridepublicAopProxycreateAopProxy(AdvisedSupportconfig)throwsAopConfigException{if(!NativeDetector.inNativeImage()&&(config.isOptimize()||config.isProxyTargetClass()||hasNoUserSuppliedProxyInterfaces(config))){Class<?>targetClass=config.getTargetClass();if(targetClass==null){thrownewAopConfigException("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.");}if(targetClass.isInterface()||Proxy.isProxyClass(targetClass)){returnnewJdkDynamicAopProxy(config);}returnnewObjenesisCglibAopProxy(config);}else{returnnewJdkDynamicAopProxy(config);}}
@OverridepublicObjectgetProxy(@NullableClassLoaderclassLoader){// ...// 拿到被代理的类Class<?>rootClass=this.advised.getTargetClass();Assert.state(rootClass!=null,"Target class must be available for creating a CGLIB proxy");Class<?>proxySuperClass=rootClass;// 如果被代理的类的本身就已经是在Cglib所生成的代理类了if(rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)){// 获取真正的被代理类proxySuperClass=rootClass.getSuperclass();// 获取被代理类所实现的接口Class<?>[]additionalInterfaces=rootClass.getInterfaces();for(Class<?>additionalInterface:additionalInterfaces){this.advised.addInterface(additionalInterface);}}// Validate the class, writing log messages as necessary.validateClassIfNecessary(proxySuperClass,classLoader);// Configure CGLIB Enhancer...Enhancerenhancer=createEnhancer();if(classLoader!=null){enhancer.setClassLoader(classLoader);if(classLoaderinstanceofSmartClassLoader&&((SmartClassLoader)classLoader).isClassReloadable(proxySuperClass)){enhancer.setUseCache(false);}}// 被代理类, 代理类的父亲enhancer.setSuperclass(proxySuperClass);// 代理类额外要实现的接口enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);enhancer.setStrategy(newClassLoaderAwareGeneratorStrategy(classLoader));// ☆ ->// 获取和被代理类所匹配的AdvisorCallback[]callbacks=getCallbacks(rootClass);Class<?>[]types=newClass<?>[callbacks.length];for(intx=0;x<types.length;x++){types[x]=callbacks[x].getClass();}// fixedInterceptorMap only populated at this point, after getCallbacks call aboveenhancer.setCallbackFilter(newProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(),this.fixedInterceptorMap,this.fixedInterceptorOffset));enhancer.setCallbackTypes(types);// Generate the proxy class and create a proxy instance.returncreateProxyClassAndInstance(enhancer,callbacks);// ...}
@OverrideprotectedList<Advisor>findCandidateAdvisors(){// Add all the Spring advisors found according to superclass rules.// 找到所有Advisor类型的Bean对象List<Advisor>advisors=super.findCandidateAdvisors();// Build Advisors for all AspectJ aspects in the bean factory.// 再从所有的切面中解析得到Advisor对象if(this.aspectJAdvisorsBuilder!=null){// 解析AspectJ中定义的切面方法, 并加到advisors中advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());}returnadvisors;}
publicList<Advisor>buildAspectJAdvisors(){List<String>aspectNames=this.aspectBeanNames;if(aspectNames==null){synchronized(this){aspectNames=this.aspectBeanNames;if(aspectNames==null){List<Advisor>advisors=newArrayList<>();aspectNames=newArrayList<>();String[]beanNames=BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory,Object.class,true,false);for(StringbeanName:beanNames){if(!isEligibleBean(beanName)){continue;}Class<?>beanType=this.beanFactory.getType(beanName,false);if(beanType==null){continue;}// 判断类上是否有AspectJ注解if(this.advisorFactory.isAspect(beanType)){aspectNames.add(beanName);// 切面的注解信息AspectMetadataamd=newAspectMetadata(beanType,beanName);// 如果@Aspect不是perthis、pertarget, 那么一个切面只会生成一个对象(单例),// 并且会将该切面中的所对应的Advisor对象进行缓存if(amd.getAjType().getPerClause().getKind()==PerClauseKind.SINGLETON){MetadataAwareAspectInstanceFactoryfactory=newBeanFactoryAspectInstanceFactory(this.beanFactory,beanName);// ☆ ->// 利用BeanFactoryAspectInstanceFactory来解析Aspect类List<Advisor>classAdvisors=this.advisorFactory.getAdvisors(factory);if(this.beanFactory.isSingleton(beanName)){// 缓存切面所对应的所有Advisor对象this.advisorsCache.put(beanName,classAdvisors);}else{this.aspectFactoryCache.put(beanName,factory);}advisors.addAll(classAdvisors);}else{// Per target or per this.if(this.beanFactory.isSingleton(beanName)){thrownewIllegalArgumentException("Bean with name '"+beanName+"' is a singleton, but aspect instantiation model is not singleton");}MetadataAwareAspectInstanceFactoryfactory=newPrototypeAspectInstanceFactory(this.beanFactory,beanName);this.aspectFactoryCache.put(beanName,factory);// 利用PrototypeAspectInstanceFactory来解析Aspect类// PrototypeAspectInstanceFactory的父类为BeanFactoryAspectInstanceFactory// 这两个Factory的区别在于PrototypeAspectInstanceFactory的构造方法中会判断切面Bean是不是原型,// 除此之外没有其他区别//// 所以主要就是BeanFactoryAspectInstanceFactory来负责生成切面实例对象advisors.addAll(this.advisorFactory.getAdvisors(factory));}}}this.aspectBeanNames=aspectNames;returnadvisors;}}}if(aspectNames.isEmpty()){returnCollections.emptyList();}// 如果切面已经找到过了,那么则遍历每个切面是否缓存了对应的Advisor,如果没有缓存则进行解析得到AdvisorList<Advisor>advisors=newArrayList<>();for(StringaspectName:aspectNames){List<Advisor>cachedAdvisors=this.advisorsCache.get(aspectName);if(cachedAdvisors!=null){advisors.addAll(cachedAdvisors);}else{MetadataAwareAspectInstanceFactoryfactory=this.aspectFactoryCache.get(aspectName);advisors.addAll(this.advisorFactory.getAdvisors(factory));}}returnadvisors;}
// 按不同的注解类型得到不同的Adviceswitch(aspectJAnnotation.getAnnotationType()){caseAtPointcut:if(logger.isDebugEnabled()){logger.debug("Processing pointcut '"+candidateAdviceMethod.getName()+"'");}returnnull;caseAtAround:springAdvice=newAspectJAroundAdvice(candidateAdviceMethod,expressionPointcut,aspectInstanceFactory);break;caseAtBefore:springAdvice=newAspectJMethodBeforeAdvice(candidateAdviceMethod,expressionPointcut,aspectInstanceFactory);break;caseAtAfter:springAdvice=newAspectJAfterAdvice(candidateAdviceMethod,expressionPointcut,aspectInstanceFactory);break;caseAtAfterReturning:springAdvice=newAspectJAfterReturningAdvice(candidateAdviceMethod,expressionPointcut,aspectInstanceFactory);AfterReturningafterReturningAnnotation=(AfterReturning)aspectJAnnotation.getAnnotation();if(StringUtils.hasText(afterReturningAnnotation.returning())){springAdvice.setReturningName(afterReturningAnnotation.returning());}break;caseAtAfterThrowing:springAdvice=newAspectJAfterThrowingAdvice(candidateAdviceMethod,expressionPointcut,aspectInstanceFactory);AfterThrowingafterThrowingAnnotation=(AfterThrowing)aspectJAnnotation.getAnnotation();if(StringUtils.hasText(afterThrowingAnnotation.throwing())){springAdvice.setThrowingName(afterThrowingAnnotation.throwing());}break;default:thrownewUnsupportedOperationException("Unsupported advice type on method: "+candidateAdviceMethod);}