在了解Spring AOP的实现之前,先了解一些Spring AOP的相关概念

AOP的相关概念

在使用Spring进行AOP相关的编程时,我们经常使用Advice (通知), PointCut (切点), Advisor (通知器)来实现我们需要的功能。

Advice

Advice是AOP联盟定义的一个接口,定义了我们可以在切点做些什么,即我们希望织入的增强逻辑,为切面增强提供织入的入口。在Spring中,Advice作为一个统一的接口,Spring在Advice的基础上定义了具体的通知类型,比如,

  • BeforeAdvice: 前置增强接口,在目标方法调用之前回调。
  • AfterAdvice : 后置增强接口,在目标方法调用结束并成功返回时回调。
  • ThrowAdvice : 在抛出异常时回调。
  • Interceptor: 表示一个通用的拦截器,可以在方法的调用前后进行增强。
  • DynamicIntroductionAdvice: 与上面的Advice和Interceptor不同,DynamicIntroductionAdvice不对方法进行增强,而是动态的引入新的接口实现。我们可以为目标类添加一个接口的实现(原来目标类未实现某个接口),那么通过DynamicIntroductionAdvice增强可以为目标类创建实现某接口的代理。

image.png

Pointcut

Pointcut 决定Advice可以作用于哪些连接点,即通过Pointcut我们可以定义需要增强的方法的集合。这些方法的集合可以通过Pointcut中定义的规则来选取,当方法符合Pointcut定义的规则时,返回true。这些规则可是正则表达式,也可以是字符串的匹配等。

Spring定义了Pointcut的接口,Pointcut接口中定义了用于获取类过滤器和方法匹配器的抽象方法。

public interface Pointcut {

    /**
     * Return the ClassFilter for this pointcut.
     * @return the ClassFilter (never {@code null})
     */
    ClassFilter getClassFilter();

    /**
     * Return the MethodMatcher for this pointcut.
     * @return the MethodMatcher (never {@code null})
     */
    MethodMatcher getMethodMatcher();


    /**
     * Canonical Pointcut instance that always matches.
     */
    Pointcut TRUE = TruePointcut.INSTANCE;

}

但是有了类过滤器和方法匹配器,我们还需要知道如何使用类过滤器和方法匹配器,因此在实现Pointcut的同时也需要实现MethodMatcher。MethodMatcher定义了matches方法,即用于规则匹配的方法。

public interface MethodMatcher {

    /**
     * Perform static checking whether the given method matches.
     * <p>If this returns {@code false} or if the {@link #isRuntime()}
     * method returns {@code false}, no runtime check (i.e. no
     * {@link #matches(java.lang.reflect.Method, Class, Object[])} call)
     * will be made.
     * @param method the candidate method
     * @param targetClass the target class
     * @return whether or not this method matches statically
     */
    boolean matches(Method method, Class<?> targetClass);

    /**
     * Is this MethodMatcher dynamic, that is, must a final call be made on the
     * {@link #matches(java.lang.reflect.Method, Class, Object[])} method at
     * runtime even if the 2-arg matches method returns {@code true}?
     * <p>Can be invoked when an AOP proxy is created, and need not be invoked
     * again before each method invocation,
     * @return whether or not a runtime match via the 3-arg
     * {@link #matches(java.lang.reflect.Method, Class, Object[])} method
     * is required if static matching passed
     */
    boolean isRuntime();

    /**
     * Check whether there a runtime (dynamic) match for this method,
     * which must have matched statically.
     * <p>This method is invoked only if the 2-arg matches method returns
     * {@code true} for the given method and target class, and if the
     * {@link #isRuntime()} method returns {@code true}. Invoked
     * immediately before potential running of the advice, after any
     * advice earlier in the advice chain has run.
     * @param method the candidate method
     * @param targetClass the target class
     * @param args arguments to the method
     * @return whether there's a runtime match
     * @see MethodMatcher#matches(Method, Class)
     */
    boolean matches(Method method, Class<?> targetClass, Object... args);


    /**
     * Canonical instance that matches all methods.
     */
    MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;

}

下图给出了Spring中一些Pointcut的继承关系,可以看到具体的实现都集成了Pointcut接口和MethodMatcher接口。
image.png

Advisor

前面介绍了Advice的增强逻辑,Pointcut定义了方法的集合,但是哪些方法使用什么样的增强逻辑依旧没有关联起来,Advisor就是将Advice和Pointcut结合起来,通过Advisor,可以定义在某个Pointcut连接点上使用哪个Advice。
Spring 提供了一个DefaultPointcutAdvisor, 在DefaultPointcutAdvisor中有两个属性,分别为advice和pointcut用来配置Advice 和Pointcut。 其实现如下所示。

public class DefaultPointcutAdvisor extends AbstractGenericPointcutAdvisor implements Serializable {

    private Pointcut pointcut = Pointcut.TRUE;


    /**
     * Create an empty DefaultPointcutAdvisor.
     * <p>Advice must be set before use using setter methods.
     * Pointcut will normally be set also, but defaults to {@code Pointcut.TRUE}.
     */
    public DefaultPointcutAdvisor() {
    }

    /**
     * Create a DefaultPointcutAdvisor that matches all methods.
     * <p>{@code Pointcut.TRUE} will be used as Pointcut.
     * @param advice the Advice to use
     */
    public DefaultPointcutAdvisor(Advice advice) {
        this(Pointcut.TRUE, advice);
    }

    /**
     * Create a DefaultPointcutAdvisor, specifying Pointcut and Advice.
     * @param pointcut the Pointcut targeting the Advice
     * @param advice the Advice to run when Pointcut matches
     */
    public DefaultPointcutAdvisor(Pointcut pointcut, Advice advice) {
        this.pointcut = pointcut;
        setAdvice(advice);
    }


    /**
     * Specify the pointcut targeting the advice.
     * <p>Default is {@code Pointcut.TRUE}.
     * @see #setAdvice
     */
    public void setPointcut(@Nullable Pointcut pointcut) {
        this.pointcut = (pointcut != null ? pointcut : Pointcut.TRUE);
    }

    @Override
    public Pointcut getPointcut() {
        return this.pointcut;
    }


    @Override
    public String toString() {
        return getClass().getName() + ": pointcut [" + getPointcut() + "]; advice [" + getAdvice() + "]";
    }

}

Spring AOP的实现

前面已经介绍了Spring AOP的相关概念,但是Spring AOP是如何对方法的调用进行拦截的呢?下面就Spring AOP的实现进行分析。
同样以Spring中的单元测试开始Spring AOP的实现分析。
通过以下代码开始Spring AOP的实现分析。

@Test
public void testProxyFactory() {
    TestBean target = new TestBean();
    ProxyFactory pf = new ProxyFactory(target);
    NopInterceptor nop = new NopInterceptor();
    CountingBeforeAdvice cba = new CountingBeforeAdvice();
    Advisor advisor = new DefaultPointcutAdvisor(cba);
    pf.addAdvice(nop);
    pf.addAdvisor(advisor);
    ITestBean proxied = (ITestBean) pf.getProxy();
    proxied.setAge(5);
    assertThat(cba.getCalls()).isEqualTo(1);
    assertThat(nop.getCount()).isEqualTo(1);
    assertThat(pf.removeAdvisor(advisor)).isTrue();
    assertThat(proxied.getAge()).isEqualTo(5);
    assertThat(cba.getCalls()).isEqualTo(1);
    assertThat(nop.getCount()).isEqualTo(2);
}

上述的代码中创建了一个TestBean,NopInterceptor, CountingBeforeAdvice对象,并使用TestBean初始化了ProxyFactory,CountingBeforeAdvice对象初始化DefaultPointcutAdvisor,同时将NopInterceptorDefaultPointcutAdvisor添加到ProxyFactory中。可以看到上述的代码中没有指明Pointcut, 也就意味着使用了默认的Pointcut.TRUE, 即对所有的方法都进行增强。

首先来看一下ProxyFactory的继承关系。

image.png

从上往下看,首先是TargetClassAware, 定义了一个getTargetClass()方法用来获取目标对象的Class,Advised继承了该接口,Advised接口定义了获取和设置AOP 代理工厂(Aop proxy factory)配置的方法,具体代码如下:

public interface Advised extends TargetClassAware {

    boolean isFrozen();

    boolean isProxyTargetClass();

    Class<?>[] getProxiedInterfaces();

    boolean isInterfaceProxied(Class<?> intf);

    void setTargetSource(TargetSource targetSource);

    TargetSource getTargetSource();

    void setExposeProxy(boolean exposeProxy);

    boolean isExposeProxy();

    void setPreFiltered(boolean preFiltered);

    boolean isPreFiltered();

    Advisor[] getAdvisors();

    default int getAdvisorCount() {
        return getAdvisors().length;
    }

    void addAdvisor(Advisor advisor) throws AopConfigException;
    
    void addAdvisor(int pos, Advisor advisor) throws AopConfigException;
    
    boolean removeAdvisor(Advisor advisor);
    
    void removeAdvisor(int index) throws AopConfigException;

    int indexOf(Advisor advisor);
    
    boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;
    
    void addAdvice(Advice advice) throws AopConfigException;
    
    void addAdvice(int pos, Advice advice) throws AopConfigException;
    
    boolean removeAdvice(Advice advice);
    
    int indexOf(Advice advice);

    String toProxyConfigString();
}

而ProxyConfig则保存了AOP 代理工厂的部分属性,可以看成是一个数据基类,如下:

public class ProxyConfig implements Serializable {
    ...
    private boolean proxyTargetClass = false;

    private boolean optimize = false;

    boolean opaque = false;

    boolean exposeProxy = false;

    private boolean frozen = false;
    ...
}

AdvisedSupport 继承了ProxyConfig同时实现了Advised接口,封装了AOP对Advice和Advisor的相关操作。

/** The AdvisorChainFactory to use. */
AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();

/** Cache with Method as key and advisor chain List as value. */
private transient Map<MethodCacheKey, List<Object>> methodCache;

/**
 * Interfaces to be implemented by the proxy. Held in List to keep the order
 * of registration, to create JDK proxy with specified order of interfaces.
 */
private List<Class<?>> interfaces = new ArrayList<>();

/**
 * List of Advisors. If an Advice is added, it will be wrapped
 * in an Advisor before being added to this List.
 */
private List<Advisor> advisors = new ArrayList<>();

ProxyCreatorSupport 则提供了设置ProxyFactory和创建代理对象的方法,创建的具体的代理对象则交给具体的ProxyFactory完成。
最下面的则是三个具体的ProxyFactory的实现,分别为:

  • ProxyFactory,可以在IOC容器中使用声明式配置AOP。
  • ProxyFactoryBean,需要编程式的使用AOP
  • AspectProxyFactory, 对于使用AspectJ的AOP应用,集成了Spring和AspectJ。

了解了ProxyFactory的继承关系后,继续往下看,我们已经知道了具体的代理的对象的创建交给具体的ProxyFactory。
我们主要关注下面用于获取代理对象的这行代码:

ITestBean proxied = (ITestBean) pf.getProxy();

ProxyFactory 的getProxy的实现如下:

public Object getProxy() {
    return createAopProxy().getProxy();
}

getProxy()调用ProxyCreatorSupport的createAopProxy()用于创建AopProxy。

protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

createAopProxy()先通过getAopProxyFactory()获取AopProxyFactory。getAopProxyFactory()直接返回一个DefaultAopProxyFactory的对象,然后调用DefaultAopProxyFactory的createAopProxy()方法创建具体的AopProxy,并传入this指针,即ProxyFactory对象本身,因为ProxyFactory继承了AdvisedSupport。

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    if (!NativeDetector.inNativeImage() &&
            (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.");
        }
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            return new JdkDynamicAopProxy(config);
        }
        return new ObjenesisCglibAopProxy(config);
    }
    else {
        return new JdkDynamicAopProxy(config);
    }
}
private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
    Class<?>[] ifcs = config.getProxiedInterfaces();
    return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
}
  • config.isOptimize():表示是否使用了优化策略,配置的属性optimize值决定;
  • config.isProxyTargetClass():表示是否是代理目标类,配置的属性proxy-target-class值决定;
  • hasNoUserSuppliedProxyInterfaces():就是在判断代理的对象是否有实现接口

当代理的是接口时,则使用JdkDynamicAopProxy,否则使用ObjenesisCglibAopProxy()。
JdkDynamicAopProxy保存了config和需要代理的接口。

public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
    Assert.notNull(config, "AdvisedSupport must not be null");
    if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
        throw new AopConfigException("No advisors and no TargetSource specified");
    }
    this.advised = config;
    this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}

当advised没有实现SpringProxy,Advised, DecoratingProxy 接口AopProxyUtils.completeProxiedInterfaces()会分别添加这三个接口。

到这里AopProxyFactory就实例化完成了。继续看getProxy()做了什么。

public Object getProxy() {
    return getProxy(ClassUtils.getDefaultClassLoader());
}
public Object getProxy(@Nullable ClassLoader classLoader) {
    if (logger.isTraceEnabled()) {
        logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
    }
    return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}

通过将classLoader, proxiedInterfaces和this传入到newProxyInstance中去创建了目标对象的代理对象。JdkDynamicAopProxy实现了InvocationHandler接口,因此可以将this指针传进去创建代理对象。

代理对象创建完成之后,当我们调用代理对象的方法时,就会回调JdkDynamicAopProxy的invoke()方法。到这里我们只看见了代理对象的创建,依旧没有看到怎么对方法进行增强的逻辑,因为对代码进行增强的实现就在invoke()方法里面。

接下来看一下invoke()方法。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object oldProxy = null;
    boolean setProxyContext = false;

    TargetSource targetSource = this.advised.targetSource;
    Object target = null;

    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        }
        else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        }
        else if (method.getDeclaringClass() == DecoratingProxy.class) {
            // There is only getDecoratedClass() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClass(this.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.
        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()) {
            // 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);
        }
    }
}

invoke()的入参为代理对象,调用的方法,以及调用方法的参数。invoke()方首先检查method是不是equal,hashCode方法,以及declaringClass是不是DecoratingProxy,是不是需要将proxy设置到AopContext里面。做完这一系列的检查之后,通过getInterceptorsAndDynamicInterceptionAdvice()获取Interceptor和Advice保存到chain中,如果chain为空,表示没有interceptor和Advice,则直接通过反射的方法调用目标方法,invokeJoinpointUsingReflection()方法封装反射调用的逻辑。如果非空,则构造一个ReflectiveMethodInvocation对象,ReflectiveMethodInvocation对象的proceed方法封装了Advice方法的增强逻辑。

先来看一下getInterceptorsAndDynamicInterceptionAdvice()的实现:

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
    MethodCacheKey cacheKey = new MethodCacheKey(method);
    List<Object> cached = this.methodCache.get(cacheKey);
    if (cached == null) {
        cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
                this, method, targetClass);
        this.methodCache.put(cacheKey, cached);
    }
    return cached;
}

先将method封装成MethodCacheKey,然后尝试从缓存中获取这个key对应的缓存,如果没有,则通过advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice()去获取,这里的advisorChainFactory的默认实现是DefaultAdvisorChainFactory,看一下getInterceptorsAndDynamicInterceptionAdvice()的实现。

public List<Object> 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();
    Advisor[] advisors = config.getAdvisors();
    List<Object> 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) {
                    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)) {
                Interceptor[] interceptors = registry.getInterceptors(advisor);
                interceptorList.addAll(Arrays.asList(interceptors));
            }
        }
        else {
            Interceptor[] interceptors = registry.getInterceptors(advisor);
            interceptorList.addAll(Arrays.asList(interceptors));
        }
    }

    return interceptorList;
}

上述的代码首先通过GlobalAdvisorAdapterRegistry.getInstance()获取了DefaultAdvisorAdapterRegistry的实例,DefaultAdvisorAdapterRegistry注册了三种Adviced的适配器,用于将Advice适配成Interceptor。

public DefaultAdvisorAdapterRegistry() {
    registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
    registerAdvisorAdapter(new AfterReturningAdviceAdapter());
    registerAdvisorAdapter(new ThrowsAdviceAdapter());
}

然后对我们添加的Advisor逐个遍历,首先判断是不是PointcutAdvisor,然后判断是不是IntroductionAdvisor,如果都不是则认为是Interceptor。如果当前的advisor是PointcutAdvisor,则先判断是不是提前过滤过了,或者class是否符合ClassFilter中定义的规则,如果进一步判断MethodMatcher的类型以及method是否匹配。无论是PointcutAdvisor,IntroductionAdvisor还是Interceptor, 最后都通过 registry.getInterceptors()方法对advisor进行适配,将advisor对象通过响应的适配器适配成MethodInterceptor的一个实例。具体的实现如下所示:

public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
    List<MethodInterceptor> interceptors = new ArrayList<>(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));
        }
    }
    if (interceptors.isEmpty()) {
        throw new UnknownAdviceTypeException(advisor.getAdvice());
    }
    return interceptors.toArray(new MethodInterceptor[0]);
}

看一下其中一个adapter的实现。

class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {

    @Override
    public boolean supportsAdvice(Advice advice) {
        return (advice instanceof MethodBeforeAdvice);
    }

    @Override
    public MethodInterceptor getInterceptor(Advisor advisor) {
        MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
        return new MethodBeforeAdviceInterceptor(advice);
    }

}

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {

    private final MethodBeforeAdvice advice;


    public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
        Assert.notNull(advice, "Advice must not be null");
        this.advice = advice;
    }


    @Override
    @Nullable
    public Object invoke(MethodInvocation mi) throws Throwable {
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        return mi.proceed();
    }

}

可以看到对于BeforeAdvice最终被是配成了MethodBeforeAdviceInterceptor,实现了MethodInterceptor接口,其中invoke方法就是后面拦截器链的入口。

继续看proceed的实现。

public Object proceed() throws Throwable {
    // We start with an index of -1 and increment early.
    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        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.
        return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    }
}

从索引为-1开始递增,如果所有的Interceptor或者Advice都调用完毕,则通过反射调用目标函数。如果当前的interceptorOrInterceptionAdvice是InterceptorAndDynamicMethodMatcher的实例,则先通matches方法进行匹配,如果匹配成功,则调用interceptor的invoke方法,否则跳过,如果不是InterceptorAndDynamicMethodMatcher的实例则时表示是一个interceptor,也直接调用invoke方法。

结合上述的MethodInterceptor的invoke方法,可以看到所有的Advice和interceptor串成了一条拦截器链,从头开始,通过matches方法进行匹配,匹配成功则进行增强,否则继续往下查找,直到尾部,调用目标方法,整个过程就是对目标方法的增强过程,也是AOP的实现原理。

总结

本文以ProxyFactory为例分析了Spring AOP的实现,其实现原理大致可以分为三个部分:

  1. Advice, Pointcut,Advisor的实现
  2. 目标对象代理对象的生成。
  3. 对Advice进行适配,并组装成一条拦截器链,通过拦截器链对目标方法进行增强。

风是客
19 声望1 粉丝