protected List<Advisor> sortAdvisors(List<Advisor> advisors) { List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = newArrayList<PartiallyComparableAdvisorHolder>(advisors.size()); for (Advisor element : advisors) { partiallyComparableAdvisors.add( newPartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR)); } List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors); if (sorted != null) { List<Advisor> result = newArrayList<Advisor>(advisors.size()); for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) { result.add(pcAdvisor.getAdvisor()); } return result; } else { returnsuper.sortAdvisors(advisors); } }
publicstatic <T extendsPartialComparable> List<T> sort(List<T> objects) { // lists of size 0 or 1 don't need any sorting if (objects.size() < 2) { return objects; }
// ??? we might want to optimize a few other cases of small size
// ??? I don't like creating this data structure, but it does give good // ??? separation of concerns. List<SortObject<T>> sortList = newLinkedList<SortObject<T>>(); for (Iterator<T> i = objects.iterator(); i.hasNext();) { addNewPartialComparable(sortList, i.next()); }
// System.out.println(sortList);
// now we have built our directed graph // use a simple sort algorithm from here // can increase efficiency later // List ret = new ArrayList(objects.size()); finalintN= objects.size(); for (intindex=0; index < N; index++) { // System.out.println(sortList); // System.out.println("-->" + ret);
SortObject<T> leastWithNoSmallers = null;
for (SortObject<T> so: sortList) { if (so.hasNoSmallerObjects()) { if (leastWithNoSmallers == null || so.object.fallbackCompareTo(leastWithNoSmallers.object) < 0) { leastWithNoSmallers = so; } } }
@Override protected 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. advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors()); return advisors; }
public List<Advisor> findAdvisorBeans() { //Determine list of advisor bean names, if not cached already. //获取所有Advisor的Bean的名字 String[] advisorNames = null; synchronized (this) { advisorNames = this.cachedAdvisorBeanNames; if (advisorNames == null) { //Do not initialize FactoryBeans here: We need to leave all regular beans //uninitialized to let the auto-proxy creator apply to them! advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this.beanFactory, Advisor.class, true, false); this.cachedAdvisorBeanNames = advisorNames; } } if (advisorNames.length == 0) { returnnewLinkedList<Advisor>(); }
List<Advisor> advisors = newLinkedList<Advisor>(); //遍历每个Advisor的名字 for (String name : advisorNames) { if (isEligibleBean(name)) { if (this.beanFactory.isCurrentlyInCreation(name)) { if (logger.isDebugEnabled()) { logger.debug("Skipping currently created advisor '" + name + "'"); } } else { try { //取出对应的Bean,添加到列表中 advisors.add(this.beanFactory.getBean(name, Advisor.class)); } catch (BeanCreationException ex) { ThrowablerootCause= ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationExceptionbce= (BeanCreationException) rootCause; if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) { if (logger.isDebugEnabled()) { logger.debug("Skipping advisor '" + name + "' with dependency on currently created bean: " + ex.getMessage()); } //Ignore: indicates a reference back to the bean we're trying to advise. //We want to find advisors other than the currently created bean itself. continue; } } throw ex; } } } } return advisors; }
public List<Advisor> buildAspectJAdvisors() { //获取所有标记了@Aspect注解的Bean的名字 List<String> aspectNames = this.aspectBeanNames;
//下面这个if子句用于初始化this.aspectBeanNames if (aspectNames == null) { synchronized (this) { aspectNames = this.aspectBeanNames; if (aspectNames == null) { List<Advisor> advisors = newLinkedList<Advisor>(); aspectNames = newLinkedList<String>(); //获取所有Bean的名字 String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this.beanFactory, Object.class, true, false); //遍历这些Bean的名字 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); if (beanType == null) { continue; }
//这里检验这个类型是否被@Aspect注解标记,或者用Aspect编译器编译过。总是就是检查是否与Aspect相关 if (this.advisorFactory.isAspect(beanType)) { aspectNames.add(beanName); AspectMetadataamd=newAspectMetadata(beanType, beanName); if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) { MetadataAwareAspectInstanceFactoryfactory= newBeanFactoryAspectInstanceFactory(this.beanFactory, beanName); List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory); if (this.beanFactory.isSingleton(beanName)) { 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); advisors.addAll(this.advisorFactory.getAdvisors(factory)); } } } this.aspectBeanNames = aspectNames; return advisors; } } }
publicstaticbooleancanApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) { //如果是IntroductionAdvisor,那么根据类过滤器进行判断即可 if (advisor instanceof IntroductionAdvisor) { return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass); } //如果是PointcutAdvisor,那么继续调用另一个重载版本进行判断 elseif (advisor instanceof PointcutAdvisor) { PointcutAdvisorpca= (PointcutAdvisor) advisor; return canApply(pca.getPointcut(), targetClass, hasIntroductions); } else { //It doesn't have a pointcut so we assume it applies. returntrue; } }
publicstaticbooleancanApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { Assert.notNull(pc, "Pointcut must not be null"); //如果类不匹配,那么直接返回false if (!pc.getClassFilter().matches(targetClass)) { returnfalse; }
MethodMatchermethodMatcher= pc.getMethodMatcher(); //如果是一个默认的单例对象,那么直接返回true if (methodMatcher == MethodMatcher.TRUE) { //No need to iterate the methods if we're matching any method anyway... returntrue; }
public Advisor wrap(Object adviceObject)throws UnknownAdviceTypeException { //如果本身就是Advisor那么直接返回即可 if (adviceObject instanceof Advisor) { return (Advisor) adviceObject; } if (!(adviceObject instanceof Advice)) { thrownewUnknownAdviceTypeException(adviceObject); } Adviceadvice= (Advice) adviceObject; if (advice instanceof MethodInterceptor) { //So well-known it doesn't even need an adapter. returnnewDefaultPointcutAdvisor(advice); } for (AdvisorAdapter adapter : this.adapters) { //Check that it is supported. //查看该Advice是否被现有的Adpater支持 if (adapter.supportsAdvice(advice)) { //封装成Advisor returnnewDefaultPointcutAdvisor(advice); } } thrownewUnknownAdviceTypeException(advice); }
try { //如果代理接口中不包含equals方法,那么直接透传,不织入增强 if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) { //The target does not implement the equals(Object) method itself. return equals(args[0]); } //如果代理接口中不包含hashCode方法,那么直接透传,不织入增强 elseif (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { //The target does not implement the hashCode() method itself. return hashCode(); } elseif (method.getDeclaringClass() == DecoratingProxy.class) { //There is only getDecoratedClass() declared -> dispatch to proxy config. return AopProxyUtils.ultimateTargetClass(this.advised); } elseif (!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. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); //由于拦截器链是空的,直接反射调用目标方法 retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse); } else { //We need to create a method invocation... //创建一个方法织入点,用于触发拦截器的调用链,该织入点包含了触发目标方法的所有内容,包括对象本身,方法参数等 invocation = newReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); //Proceed to the joinpoint through the interceptor chain. //触发拦截器的调用链 //目标对象的目标方法将会在proceed内部调用 retVal = invocation.proceed(); }
//Massage return value if necessary. Class<?> returnType = method.getReturnType(); if (retVal != null && retVal == target && returnType != Object.class && returnType.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; } elseif (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) { thrownewAopInvocationException( "Null return value from advice does not match primitive return type for: " + method); } return retVal; } finally { if (target != null && !targetSource.isStatic()) { //Must have come from TargetSource. targetSource.releaseTarget(target); } if (setProxyContext) { //Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } }
public List<Object> getInterceptorsAndDynamicInterceptionAdvice( Advised config, Method method, Class<?> targetClass) {
//This is somewhat tricky... We have to process introductions first, //but we need to preserve order in the ultimate list. List<Object> interceptorList = newArrayList<Object>(config.getAdvisors().length); Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass()); booleanhasIntroductions= hasMatchingIntroductions(config, actualClass);
public Object proceed()throws Throwable { // We start with an index of -1 and increment early. //如果拦截器已经调用完毕了,那么触发目标方法 if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { return invokeJoinpoint(); }
//获取下一个拦截器 ObjectinterceptorOrInterceptionAdvice= this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); //这个类就是之前在获取拦截器链的时候封装Method以及MethodMatcher的类 if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { //Evaluate dynamic method matcher here: static part will already have //been evaluated and found to match. InterceptorAndDynamicMethodMatcherdm= (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. //否则跳过当前拦截器,继续proceed方法 return proceed(); } } else { //It's an interceptor, so we just invoke it: The pointcut will have //been evaluated statically before this object was constructed. //否则就是MethodInterceptor接口的实现类,直接触发拦截器即可 return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); } }
public Object getProxy() { return getProxy(null); }
@Override public Object getProxy(ClassLoader classLoader) { if (logger.isDebugEnabled()) { logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource()); }
try { Class<?> rootClass = this.advised.getTargetClass(); Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
//获取回调逻辑 Callback[] 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 above enhancer.setCallbackFilter(newProxyCallbackFilter( this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset)); enhancer.setCallbackTypes(types);
//Generate the proxy class and create a proxy instance. //创建代理对象 return createProxyClassAndInstance(enhancer, callbacks); } catch (CodeGenerationException ex) { thrownewAopConfigException("Could not generate CGLIB subclass of class [" + this.advised.getTargetClass() + "]: " + "Common causes of this problem include using a final class or a non-visible class", ex); } catch (IllegalArgumentException ex) { thrownewAopConfigException("Could not generate CGLIB subclass of class [" + this.advised.getTargetClass() + "]: " + "Common causes of this problem include using a final class or a non-visible class", ex); } catch (Throwable ex) { //TargetSource.getTarget() failed thrownewAopConfigException("Unexpected AOP exception", ex); } }
private Callback[] getCallbacks(Class<?> rootClass) throws Exception { //Parameters used for optimization choices... booleanexposeProxy=this.advised.isExposeProxy(); booleanisFrozen=this.advised.isFrozen(); booleanisStatic=this.advised.getTargetSource().isStatic();
//Choose an "aop" interceptor (used for AOP calls). CallbackaopInterceptor=newDynamicAdvisedInterceptor(this.advised);
//Choose a "straight to target" interceptor. (used for calls that are //unadvised but can return this). May be required to expose the proxy. Callback targetInterceptor; if (exposeProxy) { targetInterceptor = isStatic ? newStaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) : newDynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()); } else { targetInterceptor = isStatic ? newStaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) : newDynamicUnadvisedInterceptor(this.advised.getTargetSource()); }
//Choose a "direct to target" dispatcher (used for //unadvised calls to static targets that cannot return this). CallbacktargetDispatcher= isStatic ? newStaticDispatcher(this.advised.getTargetSource().getTarget()) : newSerializableNoOp();
Callback[] mainCallbacks = newCallback[] { aopInterceptor, //for normal advice targetInterceptor, //invoke target without considering advice, if optimized newSerializableNoOp(), //no override for methods mapped to this targetDispatcher, this.advisedDispatcher, newEqualsInterceptor(this.advised), newHashCodeInterceptor(this.advised) };
Callback[] callbacks;
//If the target is a static one and the advice chain is frozen, //then we can make some optimizations by sending the AOP calls //direct to the target using the fixed chain for that method. if (isStatic && isFrozen) { Method[] methods = rootClass.getMethods(); Callback[] fixedCallbacks = newCallback[methods.length]; this.fixedInterceptorMap = newHashMap<String, Integer>(methods.length);
//TODO: small memory optimization here (can skip creation for methods with no advice) for (intx=0; x < methods.length; x++) { //获取拦截器调用链 List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass); fixedCallbacks[x] = newFixedChainStaticTargetInterceptor( chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass()); this.fixedInterceptorMap.put(methods[x].toString(), x); }
//Now copy both the callbacks from mainCallbacks //and fixedCallbacks into the callbacks array. callbacks = newCallback[mainCallbacks.length + fixedCallbacks.length]; System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length); System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length); this.fixedInterceptorOffset = mainCallbacks.length; } else { callbacks = mainCallbacks; } return callbacks; }
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)throws Throwable { ObjectoldProxy=null; booleansetProxyContext=false; Class<?> targetClass = null; Objecttarget=null; try { 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 = getTarget(); if (target != null) { targetClass = target.getClass(); }
//获取拦截器调用链 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 { //We need to create a method invocation... //否则创建一个Joinpoint来织入增强 retVal = newCglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed(); } retVal = processReturnType(proxy, target, method, retVal); return retVal; } finally { if (target != null) { releaseTarget(target); } if (setProxyContext) { //Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } }