Spring AOP源码分析

AOP源码分析

Xml文件加载过程

  1. java代码

    // 切面类
    public class LogUtil {
    
    	public void before(){
    		System.out.println("before~~~");
    	}
    
    	public void after(){
    		System.out.println("after~~~");
    	}
    
    	public void afterReturning(){
    		System.out.println("after returning~~~");
    	}
    
    
    }
    
    
    
    // 普通类,需要被代理
    public class Children {
    
    	public void cry(){
    		System.out.println("wuwuwu............");
    	}
    
    	public void smile(){
    		System.out.println("hahaha.............");
    	}
    
    }
    
  2. 配置文件内容

    <bean id="logUtil" class="com.xwdx.start.springaop.LogUtil"></bean>
    
    <bean id="children" class="com.xwdx.start.springaop.Children"></bean>
    
    <aop:config>
        <aop:aspect ref="logUtil">
            <aop:pointcut id="myPointcut" expression="execution(* *.*(..))"/>
            <aop:before method="before" pointcut-ref="myPointcut"></aop:before>
            <aop:after method="after" pointcut-ref="myPointcut"></aop:after>
            <aop:after-returning method="afterReturning" pointcut-ref="myPointcut"></aop:after-returning>
        </aop:aspect>
    </aop:config>
    
  3. 解析aop标签,注册BeanDefinition到Factory中,这一步走完后xml解析到BeanDefinition解析完成

    <aop:config>标签,解析到AspectJAwareAdvisorAutoProxyCreator对象,此类是继承自SmartInstantiationAwareBeanPostProcessor,bean初始化的前面部分会调用这个BeanPostProcessor
    key=  org.springframework.aop.config.internalAutoProxyCreator
    valud=org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator
    <aop:before> after after-returning after-throwing around等标签,都注册AspectJPointcutAdvisor对象
    key=org.springframework.aop.aspectj.AspectJPointcutAdvisor#0  因为有多个,key为0,1,2依次叠加
    value=org.springframework.aop.aspectj.AspectJPointcutAdvisor
    <aop:pointcut>标签解析到  AspectJExpressionPointcut对象
    

    先注册AspectJAwareAdvisorAutoProxyCreator对象,后注册AspectJPointcutAdvisor对象,最后注册AspectJExpressionPointcut对象

AOP对象处理过程

前面创建好了几个对象的BeanDifinition,后续初始化bean的时候会创建这几个bean

refresh()方法的 registerBeanPostProcessors(beanFactory);这个方法会创建AspectJAwareAdvisorAutoProxyCreator对象

创建bean的流程中, Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

这个方法会调用实现了InstantiationAwareBeanPostProcessor的BeanPostProcessor的applyBeanPostProcessorsBeforeInstantiation方法

因为前面创建了AspectJAwareAdvisorAutoProxyCreator对象,所以会调用AspectJAwareAdvisorAutoProxyCreator的applyBeanPostProcessorsBeforeInstantiation方法,源码如下,shouldSkip是核心方法

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    Object cacheKey = getCacheKey(beanClass, beanName);

    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        // shouldSkip是核心方法,里面会创建好AOP需要的对象
        // AspectJPointcutAdvisor对象 里面包含AbstractAspectJAdvice对象
        //   - AbstractAspectJAdvice 里面包含下面三个对象
        //     - Method对象
        //     - AspectJExpressionPointcut
        //     - AspectInstanceFactory
        // shouldSkip方法执行完,会将上面的对象都创建好
        if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }

    // Create proxy here if we have a custom TargetSource.
    // Suppresses unnecessary default instantiation of the target bean:
    // The TargetSource will handle target instances in a custom fashion.
    TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            this.targetSourcedBeans.add(beanName);
        }
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
        Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    return null;
}

代理生成过程

AOP的几个对象处理完成后,在调用Children对象的时候会生成代理对象

在填充属性populate方法后的一个方法 initializeBean(beanName, exposedObject, mbd);该方法会给Children对象创建代理

initializeBean方法会调用wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

调用到 AbstractAutoProxyCreator类的wrapIfNecessary方法,核心代码:

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    // Create proxy if we have advice.  这个方法也很重要,里面构建了Advisor数组
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        // 创建代理对象核心方法
        Object proxy = createProxy(
            bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}
// getAdviceAndAdvisorsForBean方法会跳转到findEligibleAdvisors方法,里面extendAdvisors很重要
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
    // 查询beanFactory中已有的Advisor,由于前面初始化已经有缓存AspectJPointcutAdvisor#0-2,
    // 此处会从缓存中拿到那三个cachedAdvisorBeanNames,然后通过beanFactory.getBean()初始化
    List<Advisor> candidateAdvisors = findCandidateAdvisors();
    // 查询合格的Advisors集合,做一些校验,看是否能给当前对象代理,过滤掉不需要的Advisors
    List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    // 扩展Advisors,会给list的第0个索引位置加上ExposeInvocationInterceptor.ADVISOR,顺着该方法点进去即可看到
    // 此处会跳转到AspectJAwareAdvisorAutoProxyCreator类的extendAdvisors方法
    extendAdvisors(eligibleAdvisors);
    if (!eligibleAdvisors.isEmpty()) {
        // 这个排序使用的是拓扑排序, 有向无环图
        eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    }
    return eligibleAdvisors;
}

需要注意一下extendAdvisors的类图

在此简单写一下

AspectJAwareAdvisorAutoProxyCreator 继承自 AbstractAdvisorAutoProxyCreator 继承自 AbstractAutoProxyCreator

解析标签初始化的是AspectJAwareAdvisorAutoProxyCreator对象, postProcessAfterInitialization()方法属于AbstractAutoProxyCreator类,

getAdvicesAndAdvisorsForBean()方法和findEligibleAdvisors()方法都属于AbstractAdvisorAutoProxyCreator类,

然后跳转到extendAdvisors()方法,该方法属于AspectJAwareAdvisorAutoProxyCreator

// createProxy源码
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {

    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);

    if (!proxyFactory.isProxyTargetClass()) {
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        }
        else {
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }

    // 这里的advisors就是解析aop标签得到的AspectJPointcutAdvisor对象, 
    // 默认第一个放的是ExposeInvocationInterceptor.ADVISOR
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    // 把advisors添加到proxyFactory的advisors集合中,很关键,后面会用到
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);

    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }

    // 前面设置了一些值之后,将进入到常见代理对象核心方法
    return proxyFactory.getProxy(getProxyClassLoader());
}

proxyFactory.getProxy(getProxyClassLoader())方法

public Object getProxy(@Nullable ClassLoader classLoader) {
    return createAopProxy().getProxy(classLoader);
}

protected final synchronized AopProxy createAopProxy() {
    // createAopProxy方法,这个this就是proxyFacory
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

此处分两步,一步是createAopProxy,一步是getProxy方法

DefaultAopProxyFactory的createAopProxy方法

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 此处这个config就是上面的proxyFactory对象,传入了Jdk和Cglib代理对象的构造方法中去了
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        Class<?> targetClass = config.getTargetClass();
        if (targetClass == null) {
            throw new AopConfigException("TargetSource cannot determine target class: " +
                                         "Either an interface or a target is required for proxy creation.");
        }
        // 有接口,或者代理对象,使用JDK动态代理
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            return new JdkDynamicAopProxy(config);
        }
        // 否则使用CGLIB动态代理
        return new ObjenesisCglibAopProxy(config);
    }
    else {
        return new JdkDynamicAopProxy(config);
    }
}

此处我们主要看CGLIB动态代理过程, ObjenesisCglibAopProxy的getProxy方法, 该类继承自CglibAopProxy

// CglibAopProxy类getProxy方法源码
public Object getProxy(@Nullable ClassLoader classLoader) {
    try {
        // ..........省略部分代码...............
        // Configure CGLIB Enhancer...
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader &&
                ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        enhancer.setSuperclass(proxySuperClass);
        // 此处一般会添加两个接口 SpringProxy和Advised
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));

        // getCallbacks是核心方法
        Callback[] callbacks = getCallbacks(rootClass);
        Class<?>[] types = new Class<?>[callbacks.length];
        for (int x = 0; x < types.length; x++) {
            types[x] = callbacks[x].getClass();
        }
        // fixedInterceptorMap only populated at this point, after getCallbacks call above
        enhancer.setCallbackFilter(new ProxyCallbackFilter(
            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 | IllegalArgumentException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of " + 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
        throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

// 只粘贴核心代码
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
    
    // 此处的advised就是前面的proxyFactory对象,里面的advisor属性就是前面解析到的Advisor集合
    Callback aopInterceptor = new DynamicAdvisedInterceptor(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 ?
                             new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
                             new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
    }
    else {
        targetInterceptor = (isStatic ?
                             new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
                             new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
    }

    // Choose a "direct to target" dispatcher (used for
    // unadvised calls to static targets that cannot return this).
    Callback targetDispatcher = (isStatic ?
                                 new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());

    // 这个Callback数组,第一个是DynamicAdvisedInterceptor,第二个是StaticUnadvisedInterceptor,
    // 后续还有其他的,一次放到这个数组中并在最后返回
    Callback[] mainCallbacks = new Callback[] {
        aopInterceptor,  // for normal advice
        targetInterceptor,  // invoke target without considering advice, if optimized
        new SerializableNoOp(),  // no override for methods mapped to this
        targetDispatcher, this.advisedDispatcher,
        new EqualsInterceptor(this.advised),
        new HashCodeInterceptor(this.advised)
    };

    Callback[] callbacks;

    // .........将mainCallbacks赋值为callbacks,有一些判断...........
    return callbacks;
}
createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
    Class<?> proxyClass = enhancer.createClass();
    Object proxyInstance = null;

    if (objenesis.isWorthTrying()) {
        try {
            proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
        }
        catch (Throwable ex) {
            logger.debug("Unable to instantiate proxy using Objenesis, " +
                         "falling back to regular proxy construction", ex);
        }
    }

    if (proxyInstance == null) {
        // Regular instantiation via default constructor...
        try {
            Constructor<?> ctor = (this.constructorArgs != null ?
                                   proxyClass.getDeclaredConstructor(this.constructorArgTypes) :
                                   proxyClass.getDeclaredConstructor());
            ReflectionUtils.makeAccessible(ctor);
            proxyInstance = (this.constructorArgs != null ?
                             ctor.newInstance(this.constructorArgs) : ctor.newInstance());
        }
        catch (Throwable ex) {
            throw new AopConfigException("Unable to instantiate proxy using Objenesis, " +
                                         "and regular proxy instantiation via default constructor fails as well", ex);
        }
    }

    // 前面是cglib生成动态代理类并初始化的过程, 这一步是关键步骤,设置callbacks,这个callbacks就是上面getCallbacks方法得到的Calback数组
    // 到这一步,该对象已经创建好了
    ((Factory) proxyInstance).setCallbacks(callbacks);
    return proxyInstance;
}

CGLIB生成的class文件内容

查看cglib生成字节码class文件

添加下面的设置,即可将class文件保存到本地

System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,“D:\project-springframework\spring-framework\cglibproxy”);

// 代理类反编译代码, smile方法,由此可预见最终调用的是CGLIB$CALLBACK_0.intercept()方法, 那CGLIB$CALLBACK_0是啥呢,看下面一个方法
public class Children$$EnhancerBySpringCGLIB$$5bde0238 extends Children implements SpringProxy, Advised, Factory{
    public final void smile() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$smile$0$Method, CGLIB$emptyArgs, CGLIB$smile$0$Proxy);
        } else {
            super.smile();
        }
    }
    
    public final void cry() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$cry$1$Method, CGLIB$emptyArgs, CGLIB$cry$1$Proxy);
        } else {
            super.cry();
        }
    }
    
    public final boolean equals(Object var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_5;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_5;
        }

        if (var10000 != null) {
            Object var2 = var10000.intercept(this, CGLIB$equals$2$Method, new Object[]{var1}, CGLIB$equals$2$Proxy);
            return var2 == null ? false : (Boolean)var2;
        } else {
            return super.equals(var1);
        }
    }

    // setCallbacks方法
    // 上一步createProxyClassAndInstance,最后两行代码就是调用setCallbacks方法
    // ((Factory) proxyInstance).setCallbacks(callbacks);
    // return proxyInstance;
    // CGLIB$CALLBACK_0就是DynamicAdvisedInterceptor, 
    // 上面的smile和cry方法都会调用到DynamicAdvisedInterceptor的intercept方法
    public void setCallbacks(Callback[] var1) {
        this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
        this.CGLIB$CALLBACK_1 = (MethodInterceptor)var1[1];
        this.CGLIB$CALLBACK_2 = (NoOp)var1[2];
        this.CGLIB$CALLBACK_3 = (Dispatcher)var1[3];
        this.CGLIB$CALLBACK_4 = (Dispatcher)var1[4];
        this.CGLIB$CALLBACK_5 = (MethodInterceptor)var1[5];
        this.CGLIB$CALLBACK_6 = (MethodInterceptor)var1[6];
    }
}

AOP执行过程

有上面的逻辑可以看到,具体执行Children对象的smile方法的时候,会走到DynamicAdvisedInterceptor的intercept方法 (CGLIB动态代理基本知识)

DynamicAdvisedInterceptor intercept方法源码

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    Object oldProxy = null;
    boolean setProxyContext = false;
    Object target = null;
    // 代理目标对象的包装类
    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);
        // 核心方法,获取chain集合, AOP执行过程使用的是责任链模式,该方法用来构建执行链
        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...
            // 执行核心方法
            retVal = new CglibMethodInvocation(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);
        }
    }
}

List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);方法会返回一个MethodInterceptor数组

本示例中,从前到后分别为ExposeInvocationInterceptor AfterReturningAdviceInterceptor AspectJAfterAdvice MethodBeforeAdviceInterceptor

有了这个链之后,在proceed方法中

// CglibMethodInvocation类的proceed方法
private static class CglibMethodInvocation extends ReflectiveMethodInvocation {
    public Object proceed() throws Throwable {
        try {
            // 直接调用父类, ReflectiveMethodInvocation的proceed
            return super.proceed();
        }
        catch (RuntimeException ex) {
            throw ex;
        }
        catch (Exception ex) {
            if (ReflectionUtils.declaresException(getMethod(), ex.getClass()) ||
                KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) {
                // Propagate original exception if declared on the target method
                // (with callers expecting it). Always propagate it for Kotlin code
                // since checked exceptions do not have to be explicitly declared there.
                throw ex;
            }
            else {
                // Checked exception thrown in the interceptor but not declared on the
                // target method signature -> apply an UndeclaredThrowableException,
                // aligned with standard JDK dynamic proxy behavior.
                throw new UndeclaredThrowableException(ex);
            }
        }
    }
}

ReflectiveMethodInvocation类的proceed方法源码

public Object proceed() throws Throwable {
    // We start with an index of -1 and increment early.
    // interceptorsAndDynamicMethodMatchers是上面构建好的chain链, currentInterceptorIndex默认值是-1
    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        // 如果链里面的MethodInterceptor都执行完了,就执行原始类的方法
        return invokeJoinpoint();
    }

    Object interceptorOrInterceptionAdvice =
        this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
    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.
        // invoke方法是开始执行链条,依次调用chain集合中的每一个MethodInterceptor对象的invoke方法
        // 注意this, 将当前类当参数传进去了,后面每个MethodInterceptor会调用mi.proceed则会又回到当前方法中
        return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    }
}

ExposeInvocationInterceptor执行过程

public Object invoke(MethodInvocation mi) throws Throwable {
    // invocation是一个ThreadLocal属性,用于将ReflectiveMethodInvocation类的对象放到ThreadLocal中
    MethodInvocation oldInvocation = invocation.get();
    invocation.set(mi);
    try {
        // 回到ReflectiveMethodInvocation的proceed方法中,
        // 此时可以看到ReflectiveMethodInvocation的索引currentInterceptorIndex为0,
        // 然后this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        // 会取到第二个MethodInterceptor,为AfterReturningAdviceInterceptor,开始执行AfterReturningAdviceInterceptor的invoke方法
        return mi.proceed();
    }
    finally {
        invocation.set(oldInvocation);
    }
}

AfterReturningAdviceInterceptor执行过程

public Object invoke(MethodInvocation mi) throws Throwable {
    // 继续执行ReflectiveMethodInvocation的proceed方法,当执行完成后再执行afterReturning方法,因此先跳转到AspectJAfterAdvice的invoke方法中
    Object retVal = mi.proceed();
    this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
    return retVal;
}

AspectJAfterAdvice执行过程

public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        // 继续执行ReflectiveMethodInvocation的proceed方法,
        // 跳转到chain链的下一个MethodInterceptor的invoke -> MethodBeforeAdviceInterceptor
        return mi.proceed();
    }
    finally {
        // 执行完成后再执行finally中的invokeAdviceMethod(getJoinPointMatch(), null, null);方法
        invokeAdviceMethod(getJoinPointMatch(), null, null);
    }
}

MethodBeforeAdviceInterceptor执行过程

public Object invoke(MethodInvocation mi) throws Throwable {
    // 由于是before,所以先调用before增强方法,再回到ReflectiveMethodInvocation的proceed方法
    // 此处的before方法就是调用到<aop:before method="before" pointcut-ref="myPointcut"></aop:before>配置的方法
    //     -> LogUtil的before方法
    this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
    // 回到mi.proceed()方法后,由于此时索引已经到了最后一个,会执行return invokeJoinpoint();
    // invokeJoinpoint()方法就是调用原始代理方法,比如Children的smile方法,执行完后,会再往上面的MethodInterceptor依次执行
    //     执行AspectJAfterAdvice的invoke方法的finally代码块,也就是配置的<aop:after>
    //     执行AfterReturningAdviceInterceptor的invoke方法的advice.afterReturning,也就是配置的<aop:after-returning>
    //     执行ExposeInvocationInterceptor的invoke方法的inally代码块,整个AOP执行完毕
    return mi.proceed();
}

补充

由于本示例中未配置after-throwing过程,再次补充一下,配置了after-throwing会添加AspectJAfterThrowingAdvice对象到chain中

下面看看AspectJAfterThrowingAdvice的invoke方法

public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        // 跟其他几个MethodInterceptor一样的处理逻辑
        return mi.proceed();
    }
    catch (Throwable ex) {
        if (shouldInvokeOnThrowing(ex)) {
            // 执行after-throwing配置的增强方法
            invokeAdviceMethod(getJoinPointMatch(), null, ex);
        }
        throw ex;
    }
}

总结

AOP执行过程比较复杂,简单总结一下基本步骤:

  1. 加载xml,解析标签,创建一些基本对象,
  2. 实例化spring bean的时候调用BeanPostProcessor,处理需要被代理的bean
  3. 通过jdk或者cglib生成代理对象
  4. 调用代理对象方法的时候,执行DynamicAdvisedInterceptor的intercept方法,该方法会构建一个MethodInterceptor链,依次执行invoke方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值