spring 註解aop調用invoke()

public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:config" + "/spring/applicationContext-core2.xml");
        MyService as = (MyService) context.getBean("annotationServiceImpl");
        as.doSomething("Jack");  //aop起做用,com.zhuguang.jack.annotation.AnnotationServiceImpl@1c55f277,裏面的h = org.springframework.aop.framework.JdkDynamicAopProxy@50c6911c,h裏面的advised = ProxyFactory = 1 interfaces [MyService]; 4 advisors [ExposeInvocationInterceptor.ADVISOR, InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void afterrr(JoinPoint)]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void arounddd(ProceedingJoinPoint) ]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void beforeee(JoinPoint)]; ]; targetSource [AnnotationServiceImpl@1c55f277]]; 
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        TargetSource targetSource = this.advised.targetSource;    //AnnotationServiceImpl,被代理的類,
        Class<?> targetClass = null;
        Object target = null;
        try {
            if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {   //調用的方法是equals方法,就直接調用了,不用代理了。
                return equals(args[0]);
            }
            if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { //調用的方法是hashCode方法,就直接調用了,不用代理了。
                return hashCode();
            }
            if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                    method.getDeclaringClass().isAssignableFrom(Advised.class)) {//調用的方法是,,就直接調用了,不用代理了。
                return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
            }
            Object retVal;
            target = targetSource.getTarget();
            if (target != null) {
                targetClass = target.getClass();//class com.zhuguang.jack.annotation.AnnotationServiceImpl
            }
            List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);   //advised = ProxyFactory代理工廠, [public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()]這些切面已經加到工廠裏面去了, [ExposeInvocationInterceptor@65aa6596, AspectJAfterAdvice: advice method [public void afterrr()]; aspect name 'aspectAnnotation', AspectJAroundAdvice: advice method [public void arounddd() ]; aspect name 'aspectAnnotation', MethodBeforeAdviceInterceptor@1ce61929] else {
                invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
                retVal = invocation.proceed();   //調用,invocation = ReflectiveMethodInvocation,
            }
            Class<?> returnType = method.getReturnType();   //返回值
            return retVal;
        }
    }
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) {
        MethodCacheKey cacheKey = new MethodCacheKey(method);   //doSomething方法,
        List<Object> cached = this.methodCache.get(cacheKey);
        if (cached == null) {
            cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClass);
            this.methodCache.put(cacheKey, cached);
        }
        return cached;
    }
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
            Advised config, Method method, Class<?> targetClass) {  //config = ProxyFactory,method = doSomething(),targetClass = AnnotationServiceImpl

        List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);
        boolean hasIntroductions = hasMatchingIntroductions(config, targetClass);
        AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
        for (Advisor advisor : config.getAdvisors()) {//[ExposeInvocationInterceptor.ADVISOR, InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void afterrr()]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void arounddd() ]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void beforeee()]] if (advisor instanceof PointcutAdvisor) {
                PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;  //AspectAnnotation.afterrr,AspectAnnotation.arounddd,AspectAnnotation.beforeee,
                if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(targetClass)) {   //在不在Pointcut的表達式裏面,匹配的是類。
                    MethodInterceptor[] interceptors = registry.getInterceptors(advisor);  //AspectAnnotation.afterrr,
                    MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();  //AspectJExpressionPointcut: () pc1(),
                    if (MethodMatchers.matches(mm, method, targetClass, hasIntroductions)) {  //前面匹配的是類,這裏匹配的是方法。
                        else {
                            interceptorList.addAll(Arrays.asList(interceptors));
                        }
                    }
                }
            }
        }
        return interceptorList;
    }
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
        List<MethodInterceptor> interceptors = new ArrayList<MethodInterceptor>(3);
        Advice advice = advisor.getAdvice();
        if (advice instanceof MethodInterceptor) {
            interceptors.add((MethodInterceptor) advice);
        }
        for (AdvisorAdapter adapter : this.adapters) {
            if (adapter.supportsAdvice(advice)) {
                interceptors.add(adapter.getInterceptor(advisor));
            }
        }
        return interceptors.toArray(new MethodInterceptor[interceptors.size()]);
    }
public Object proceed() throws Throwable { 
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {   //索引是最後一個就調用被代理類的方法,interceptorsAndDynamicMethodMatchers = [ExposeInvocationInterceptor.ADVISOR, InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void afterrr()]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void arounddd() ]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void beforeee()]] return invokeJoinpoint();    //被代理類的方法
        }

        Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);  //根據索引拿到第一個,第二個,。。

        else { 
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);   //鏈是調用,this = invocation = ReflectiveMethodInvocation,
        }
    }
ExposeInvocationInterceptor類的invoke()方法 public Object invoke(MethodInvocation mi) throws Throwable {
        MethodInvocation oldInvocation = invocation.get();
        invocation.set(mi);
        try {
            return mi.proceed();   //mi = invocation = ReflectiveMethodInvocation,又調會去了,拿到第二個。
        }
        finally {
            invocation.set(oldInvocation);
        }
    }
AspectAnnotation.afterrr(org.aspectj.lang.JoinPoint) 類: public Object invoke(MethodInvocation mi) throws Throwable {
        try {
            return mi.proceed();   //mi = invocation = ReflectiveMethodInvocation,又調會去了,拿到第三個。after因此如今不會執行。
        }
        finally {
            invokeAdviceMethod(getJoinPointMatch(), null, null);
        }
    }
AspectAnnotation.arounddd(org.aspectj.lang.ProceedingJoinPoint)類 public Object invoke(MethodInvocation mi) throws Throwable {
        ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;//mi = invocation = ReflectiveMethodInvocation,
        ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
        JoinPointMatch jpm = getJoinPointMatch(pmi);
        return invokeAdviceMethod(pjp, jpm, null, null);
    }
protected Object invokeAdviceMethod(JoinPoint jp, JoinPointMatch jpMatch, Object returnValue, Throwable t)
            throws Throwable {
        return invokeAdviceMethodWithGivenArgs(argBinding(jp, jpMatch, returnValue, t));
    }

protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
        try {
            ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
            return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
        }
public Object invoke(Object obj, Object... args)
    {
        MethodAccessor ma = methodAccessor;             // read volatile
        if (ma == null) {
            ma = acquireMethodAccessor();
        }
        return ma.invoke(obj, args);
    }
調到了
public void arounddd(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("==============arounddd  前置通知=========");
        joinPoint.proceed();  //MethodBeforeAdviceInterceptor去執行,
        System.out.println("==============arounddd  後置通知=========");
    }
public Object invoke(MethodInvocation mi) throws Throwable {
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );//beforeee()方法執行,
        return mi.proceed();   //  被代理類的方法執行,
    }
 public void beforeee(JoinPoint joinPoint) {
        System.out.println("==============beforeee 前置通知=========");
    }
public String doSomething(String param) {
        System.out.println("==========AnnotationServiceImpl.doSomething=========");
        return "==========AnnotationServiceImpl.doSomething";
    }
最後執行after:
invokeAdviceMethod(getJoinPointMatch(), null, null);
protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
        try {
            ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
            return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
        }
    }

public Object invoke(Object obj, Object... args)
    {
        MethodAccessor ma = methodAccessor;             // read volatile
        if (ma == null) {
            ma = acquireMethodAccessor();
        }
        return ma.invoke(obj, args);
    }

public void afterrr(JoinPoint joinPoint) {
        System.out.println("==============afterrr 後置通知=========");
    }
==============arounddd  前置通知=========
==============beforeee 前置通知=========
==========AnnotationServiceImpl.doSomething=========
==============arounddd  後置通知=========
==============afterrr 後置通知=========
cglib的代理 return proxyFactory.getProxy(this.proxyClassLoader);
public Object getProxy(ClassLoader classLoader) {
        try {
            Class<?> rootClass = this.advised.getTargetClass();   //advised = ProxyFactory 

            Class<?> proxySuperClass = rootClass;  //AnnotationServiceImpl

            Callback[] callbacks = getCallbacks(rootClass);//[CglibAopProxy$DynamicAdvisedInterceptor@2ce86164, CglibAopProxy$StaticUnadvisedInterceptor@5e8f9e2d, CglibAopProxy$SerializableNoOp@51df223b, CglibAopProxy$StaticDispatcher@fd46303, CglibAopProxy$AdvisedDispatcher@60d8c0dc, CglibAopProxy$EqualsInterceptor@4204541c, CglibAopProxy$HashCodeInterceptor@6a62689d]
            Class<?>[] types = new Class<?>[callbacks.length];
            for (int x = 0; x < types.length; x++) {
                types[x] = callbacks[x].getClass();
            } 
            enhancer.setCallbackFilter(new ProxyCallbackFilter(
                    this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
            enhancer.setCallbackTypes(types); 
            return createProxyClassAndInstance(enhancer, callbacks);
        }
    }
調用方法時候:
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            try {
                List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);    // [ExposeInvocationInterceptor@65aa6596, AspectJAfterAdvice: advice method [public void afterrr()]; aspect name 'aspectAnnotation', AspectJAroundAdvice: advice method [public void arounddd() ]; aspect name 'aspectAnnotation', MethodBeforeAdviceInterceptor@1ce61929]
                Object retVal; 
                if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) { 
                    retVal = methodProxy.invoke(target, args);
                }
                else {
                    // We need to create a method invocation...
                    retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
                }
                retVal = processReturnType(proxy, target, method, retVal);
                return retVal;
            } 
        }
public Object proceed() throws Throwable { 
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }

        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); 
        else { 
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }
相關文章
相關標籤/搜索