aop执行过程核心源码分析-25

@Override
    protected List findCandidateAdvisors() {
        // Add all the Spring advisors found according to superclass rules.
        //dk 找出事务相关的advisor
        List advisors = super.findCandidateAdvisors();
        // Build Advisors for all AspectJ aspects in the bean factory.
        //dk 找出aspect
        if (this.aspectJAdvisorsBuilder != null) {
            advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
        }
        return advisors;
    }

@Aspect
@ComponentScan("com.xx")
@EnableAspectJAutoProxy(exposeProxy=true)
@Order(2)   //dk 默认的级别是最低的 Integer.MAX_VALUE,切面的执行顺序优先事务
public class AppConfig {
​

@Override
    @Nullable
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object oldProxy = null;
        boolean setProxyContext = false;
        
        //dk student
        TargetSource targetSource = this.advised.targetSource;
        Object target = null;
​
        try {
            //dk true && false  判断是否是equal方法
            if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
                // The target does not implement the equals(Object) method itself.
                return equals(args[0]);
            }
            //dk 判断是否是hashcode
            else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
                // The target does not implement the hashCode() method itself.
                return hashCode();
            }
            //dk 判断是否是DecoratingProxy方法
            else if (method.getDeclaringClass() == DecoratingProxy.class) {
                // There is only getDecoratedClass() declared -> dispatch to proxy config.
                return AopProxyUtils.ultimateTargetClass(this.advised);
            }
            //dk 判断是否是接口 &&判断是否是Advised的子类
            else 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;
            }
​
            // Get as late as possible to minimize the time we "own" the target,
            // in case it comes from a pool.
            //dk student
            target = targetSource.getTarget();
            //dk student
            Class targetClass = (target != null ? target.getClass() : null);
​
            // Get the interception chain for this method.
            List 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...
                MethodInvocation 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.
            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;
            }
            else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
                throw new AopInvocationException(
                        "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 getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class targetClass) {
        // method =say()
        MethodCacheKey cacheKey = new MethodCacheKey(method);
        //dk methodCache 里面为toString
        List cached = this.methodCache.get(cacheKey);
        if (cached == null) {
            cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
                    this, method, targetClass);
            //dk cachekey=say cached=6,也就是say里面有6个通知
            this.methodCache.put(cacheKey, cached);
        }
        return cached;
    } 
  

@Override
    public List getInterceptorsAndDynamicInterceptionAdvice(
            Advised config, Method method, @Nullable Class targetClass) {
​
        // This is somewhat tricky... We have to process introductions first,
        // but we need to preserve order in the ultimate list.
        AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
        //dk 6个,1个系统的+5个自定义的
        Advisor[] advisors = config.getAdvisors();
        List interceptorList = new ArrayList<>(advisors.length);
        Class actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
        Boolean hasIntroductions = null;
​
        for (Advisor advisor : advisors) {
            if (advisor instanceof PointcutAdvisor) {
                // Add it conditionally.
                PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
                if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
                    MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
                    boolean match;
                    if (mm instanceof IntroductionAwareMethodMatcher) {
                        if (hasIntroductions == null) {
                            hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
                        }
                        match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
                    }
                    else {
                        match = mm.matches(method, actualClass);
                    }
                    if (match) {
                        //dk 根据advisor获取interceptors
                        MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                        if (mm.isRuntime()) {
                            // Creating a new object instance in the getInterceptors() method
                            // isn't a problem as we normally cache created chains.
                            for (MethodInterceptor interceptor : interceptors) {
                                interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
                            }
                        }
                        else {
                            interceptorList.addAll(Arrays.asList(interceptors));
                        }
                    }
                }
            }
            else if (advisor instanceof IntroductionAdvisor) {
                IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
                if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
                    //dk 根据advisor获得interceptors
                    Interceptor[] interceptors = registry.getInterceptors(advisor);
                    //dk 将interceptor放入list中
                    interceptorList.addAll(Arrays.asList(interceptors));
                }
            }
            else {
                Interceptor[] interceptors = registry.getInterceptors(advisor);
                interceptorList.addAll(Arrays.asList(interceptors));
            }
        }
        //dk 返回6个通知
        return interceptorList;
    } 
  

@Override
    @Nullable
    public Object proceed() throws Throwable {
        // We start with an index of -1 and increment early.
        //dk 如果是-1 则停止责任链,执行业务逻辑
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }
        
        //dk 先第0个,系统的
        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        //dk 第一个系统的不执行
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            // Evaluate dynamic method matcher here: static part will already have
            // been evaluated and found to match.
            InterceptorAndDynamicMethodMatcher dm =
                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            Class targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
            if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
                return dm.interceptor.invoke(this);
            }
            else {
                // Dynamic matching failed.
                // Skip this interceptor and invoke the next in the chain.
                return proceed();
            }
        }
        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);
        }
    }

6个链的顺序:系统->around->before->after-afterreturning-afterthrow

1.系统

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        MethodInvocation oldInvocation = invocation.get();
        invocation.set(mi);
        try {
            //dk 再次执行处理链下一级处理链
            return mi.proceed();
        }
        finally {
            invocation.set(oldInvocation);
        }
    }

around处理逻辑,会调用around的 pjp.proceed()之前业务逻辑

@Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        if (!(mi instanceof ProxyMethodInvocation)) {
            throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
        }
        ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
        ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
        JoinPointMatch jpm = getJoinPointMatch(pmi);
        return invokeAdviceMethod(pjp, jpm, null, null);
    }

继续执行下一级执行链路,也就是before

    @Override
    public Object proceed() throws Throwable {
        return this.methodInvocation.invocableClone().proceed();
    }

before

@Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        //dk 执行before的业务逻辑
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        //处理下一级链路
        return mi.proceed();
    }

after 一定会执行后面的

@Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        try {
            //dk 执行下一级,afterreturning
            return mi.proceed();
        }
        finally {
            //dk 最后执行after
            invokeAdviceMethod(getJoinPointMatch(), null, null);
        }
    }

afterreturning,出现异常不往下执行

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        //dk 下一级执行链afterthrowing 
        Object retVal = mi.proceed();
        //dk 执行自己的逻辑
        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
        return retVal;
    }

afterthrowing 出现异常会往下执行

@Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        try {
        //dk 继续执行下一级,此时为最后一个,所以调用链结束了,要执行自己的业务逻辑
            return mi.proceed();
        }
        catch (Throwable ex) {
        //dk 此时出现了异常就不会执行afterreturning的业务逻辑,但一定会执行after的业务逻辑
        //dk 因为after用了finally,没有出现异常就会到afterreturning里面继续执行
            if (shouldInvokeOnThrowing(ex)) {
                //dk 执行自己的异常throwing逻辑
                invokeAdviceMethod(getJoinPointMatch(), null, ex);
            }
            //dk 继续抛出异常,出现异常只会执行after,异常会往上层抛出,所以不会执行around after的代码
            throw ex;
        }
    }
​

执行链路为5的话,执行自定义业务

if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }

//dk 执行自己的逻辑

    @Nullable
    protected Object invokeJoinpoint() throws Throwable {
        return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments);
    }

反射执行自己的业务

public static Object invokeJoinpointUsingReflection(@Nullable Object target, Method method, Object[] args)
            throws Throwable {
​
        // Use reflection to invoke the method.
        try {
            ReflectionUtils.makeAccessible(method);
            return method.invoke(target, args);
        }

综上所述,aop执行顺序:

around pjp before->before->业务->aftertreturnning(无异常)-after->around after

around pjp before->before-业务->afterThrowing(有异常)->after

你可能感兴趣的:(java)