//这里的逻辑是,增强器是AspectJPointcutAdvisor类型并且beanName和增强器名称一样的时候,这时候就会跳过,返回true,跳过的话回将对应的Bean标记为false,一般的Bean都不会标记为false的@OverrideprotectedbooleanshouldSkip(Class<?> beanClass, String beanName){// TODO: Consider optimization by caching the list of the aspect names
List<Advisor> candidateAdvisors =findCandidateAdvisors();for(Advisor advisor : candidateAdvisors){if(advisor instanceofAspectJPointcutAdvisor&&((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)){returntrue;}}returnsuper.shouldSkip(beanClass, beanName);}
@Overrideprotected List<Advisor>findCandidateAdvisors(){// Add all the Spring advisors found according to superclass rules.
List<Advisor> advisors =super.findCandidateAdvisors();// Build Advisors for all AspectJ aspects in the bean factory.if(this.aspectJAdvisorsBuilder != null){//这里面buildAspectJAdvisors是获取增强器的关键
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());}return advisors;}
//缓存已经解析过的切面类名称@Nullableprivatevolatile List<String> aspectBeanNames;public List<Advisor>buildAspectJAdvisors(){//1.切面类只会解析一次,解析后会缓存起来
List<String> aspectNames =this.aspectBeanNames;//2.List aspectNames保存了全部切面类的名称,首次是空的,会将切面类的名称加进去,后面再进来就会走后面的获取逻辑,不需要再次解析了if(aspectNames == null){synchronized(this){
aspectNames =this.aspectBeanNames;if(aspectNames == null){
List<Advisor> advisors =newLinkedList<>();
aspectNames =newLinkedList<>();//得到全部的Bean,并进行遍历处理,这里的类型是Object因此会获取全部的Bean
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class,true,false);//遍历处理for(String beanName : beanNames){//不是这种类型不处理if(!isEligibleBean(beanName)){continue;}// We must be careful not to instantiate beans eagerly as in this case they// would be cached by the Spring container but would not have been weaved.
Class<?> beanType =this.beanFactory.getType(beanName);//null类型不处理if(beanType == null){continue;}//是Aspect类型的Bean才处理,这里面的判断其实就是一句话:return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));包含Aspect切面注解,并且字段名称不能以ajc$开头//如果不满足,则不会处理,外面的循环一直等到LogAspect出现,才开始进去下面的逻辑进行处理if(this.advisorFactory.isAspect(beanType)){//把Aspect切面类的名字加到集合
aspectNames.add(beanName);
AspectMetadata amd =newAspectMetadata(beanType, beanName);if(amd.getAjType().getPerClause().getKind()== PerClauseKind.SINGLETON){
MetadataAwareAspectInstanceFactory factory =newBeanFactoryAspectInstanceFactory(this.beanFactory, beanName);//获取切面类的增强方法
List<Advisor> classAdvisors =this.advisorFactory.getAdvisors(factory);//Bean是单例的,就加入到缓存if(this.beanFactory.isSingleton(beanName)){this.advisorsCache.put(beanName, classAdvisors);}else{//反之就把factory加到缓存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");}
MetadataAwareAspectInstanceFactory factory =newPrototypeAspectInstanceFactory(this.beanFactory, beanName);this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));}}}this.aspectBeanNames = aspectNames;return advisors;}}}//如果是空的,就返回空集合if(aspectNames.isEmpty()){return Collections.emptyList();}//如果不是空的,就把全部的切面类对应的增强器Advisor全部遍历出来,打包返回
List<Advisor> advisors =newLinkedList<>();for(String aspectName : aspectNames){
List<Advisor> cachedAdvisors =this.advisorsCache.get(aspectName);if(cachedAdvisors != null){
advisors.addAll(cachedAdvisors);}else{
MetadataAwareAspectInstanceFactory factory =this.aspectFactoryCache.get(aspectName);
advisors.addAll(this.advisorFactory.getAdvisors(factory));}}//返回所有切面类的增强器的集合return advisors;}
//getAdvisors辅助类,获取增强器,里面会遍历切面类的全部方法,转换为增强器@Overridepublic List<Advisor>getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory){//获取切面类名称
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();validate(aspectClass);// We need to wrap the MetadataAwareAspectInstanceFactory with a decorator// so that it will only instantiate once.
MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =newLazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);//获取切面类的全部方法,将方法转换为增强对象Advisor
List<Advisor> advisors =newLinkedList<>();//这里的getAdvisorMethods会返回切面类的全部方法,但是会排除掉一种方法不返回,就是标记了@Pointcut的方法不返回,//这里容易理解,因为我们是要获取增强的方法,也就是目标方法前后的那些方法,但是@Pointcut//是用来定义对哪些方法进行拦截的,因此这里是不需要的,不过对于那些其他的方法,比如继承自Object的方法,//这里也一并返回了,不过这些方法在获取Advisor对象的时候会是null,因此并没有影响 for(Method method :getAdvisorMethods(aspectClass)){//这个getAdvisor里面会根据切面类里面的方法,获取方法的表达式,最后返回一个增强对象Advisor,Advisor里面封装了切面方法,切面类等很多信息//对于非增强的方法,因此注解上的切面表达式是null,因此在getAdvisor里面会返回null//最后advisors里面就是增强方法对于的封装后的增强对象,在LogAspect里面有5个增强方法,对于的advisors集合里面也有五个元素
Advisor advisor =getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);if(advisor != null){
advisors.add(advisor);}}// If it's a per target aspect, emit the dummy instantiating aspect.if(!advisors.isEmpty()&& lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()){
Advisor instantiationAdvisor =newSyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
advisors.add(0, instantiationAdvisor);}// Find introduction fields.//这里还会处理字段增强器for(Field field : aspectClass.getDeclaredFields()){
Advisor advisor =getDeclareParentsAdvisor(field);if(advisor != null){
advisors.add(advisor);}}return advisors;}
@Override@Nullablepublic Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)throws Throwable {
Object oldProxy = null;boolean setProxyContext =false;
Object target = null;//1.获取目标方法拦截器链//返回空
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())){// 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.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = methodProxy.invoke(target, argsToUse);}else{//拦截链不为空,使用CglibMethodInvocation对象的proceed调用目标方法//这里将目标对象,目标方法,拦截器链等信息都传入给了CglibMethodInvocation对象,proceed是重点// We need to create a method invocation...
retVal =newCglibMethodInvocation(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);}}}
ReflectiveMethodInvocation#proceed():方法,
@Override@Nullablepublic Object proceed()throws Throwable {// We start with an index of -1 and increment early.//currentInterceptorIndex默认-1,记录当前拦截器索引,右边的值是5,也就是增强器的个数if(this.currentInterceptorIndex ==this.interceptorsAndDynamicMethodMatchers.size()-1){returninvokeJoinpoint();}//索引自增,执行完最后一个的时候才会走前面的返回逻辑,
Object interceptorOrInterceptionAdvice =this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);if(interceptorOrInterceptionAdvice instanceofInterceptorAndDynamicMethodMatcher){// 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.returnproceed();}}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);}}
@Override@Nullablepublic Object proceed()throws Throwable {// We start with an index of -1 and increment early.//currentInterceptorIndex首次是-1,this.interceptorsAndDynamicMethodMatchers.size() - 1是5,只有最后一次才会进去这个逻辑if(this.currentInterceptorIndex ==this.interceptorsAndDynamicMethodMatchers.size()-1){returninvokeJoinpoint();}//一次获取方法拦截器,拦截器的顺序是前面的2.1.1 - 2.1.6那六个,顺序都是一致的
Object interceptorOrInterceptionAdvice =this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);//这里调试都会走到else的逻辑if(interceptorOrInterceptionAdvice instanceofInterceptorAndDynamicMethodMatcher){// 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.returnproceed();}}else{//会调用对应拦截器的invoke方法// 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);}}
//JdkDynamicAopProxy#invokepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;boolean setProxyContext =false;
TargetSource targetSource =this.advised.targetSource;
Object target = null;try{//Object的方法,或者其他的方法处理,代码省略...
Object retVal;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);// 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()){//没有增强,代码省略...}else{//增强,我们看到这里的逻辑和Cglib的实现是一模一样的// We need to create a method invocation...
invocation =newReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();}// Massage return value if necessary.
Class<?> returnType = method.getReturnType();if(retVal != null && retVal == target &&
retVal = proxy;}elseif(retVal == null && returnType != Void.TYPE && returnType.isPrimitive()){thrownewAopInvocationException("Null return value from advice does not match primitive return type for: "+ method);}return retVal;}//省略...}