美文网首页Spring源码分析
2.SpringAop之AdvisedSupport

2.SpringAop之AdvisedSupport

作者: 土豆肉丝盖浇饭 | 来源:发表于2018-01-23 20:10 被阅读8次

1.类继承结构

image

2.解析

AdvisedSupport继承ProxyConfig,自身提供了以下功能

  1. 配置当前代理的Adivsiors
  2. 配置当前代理的目标对象
  3. 配置当前代理的接口
  4. 提供getInterceptorsAndDynamicInterceptionAdvice方法用来获取对应代理方法对应有效的拦截器集合

AdvisedSupport本身不会提供创建代理的任何方法,代理创建由子类实现

我们来探究下第4点中的拦截器是什么东西,以及getInterceptorsAndDynamicInterceptionAdvice的源码实现

先看下拦截器(MethodInterceptor)的接口定义

public interface MethodInterceptor extends Interceptor {
    
    Object invoke(MethodInvocation invocation) throws Throwable;
}

拦截器的作用是封装在目标方法前后执行相应的逻辑,在Aop中的前置,后置,环绕等通知都有对应拦截器实现

再来看下MethodInvocation的定义

image
MethodInvocation中proceed方法比较重要
/**
* Proceeds to the next interceptor in the chain.
*
* <p>The implementation and the semantics of this method depends
* on the actual joinpoint type (see the children interfaces).
*
* @return see the children interfaces' proceed definition.
*
* @throws Throwable if the joinpoint throws an exception. */
Object proceed() throws Throwable;

proceed()方法封装了调用下一个拦截器的逻辑,如果没有拦截器,就执行被代理方法。
目前在spring框架里面MethodInvocation接口的实现类只有一个,就是ReflectiveMethodInvocation
看下它的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;
        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.
            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);
    }
}

这里会依次执行拦截器,最后执行被代理的方法
其中InterceptorAndDynamicMethodMatcher为动态拦截器,根据运行时参数来决定拦截器是否生效
有动态拦截器当然也有静态拦截器,静态拦截器一般通过包名,类名,方法名 ,参数来确定静态拦截器是否对代理方法生效

接下来讲解getInterceptorsAndDynamicInterceptionAdvice的实现

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, 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;
}

getInterceptorsAndDynamicInterceptionAdvice用来获取代理方法所对应的拦截器集合,其内部根据方法名字做了缓存,获取拦截器集合主要委托给DefaultAdvisorChainFactory来实现

public interface AdvisorChainFactory {

    /**
     * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects
     * for the given advisor chain configuration.
     * @param config the AOP configuration in the form of an Advised object
     * @param method the proxied method
     * @param targetClass the target class (may be {@code null} to indicate a proxy without
     * target object, in which case the method's declaring class is the next best option)
     * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
     */
    List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class<?> targetClass);

}

在DefaultAdvisorChainFactory的getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class<?> targetClass)方法中,遍历AdviseSupport里面配置的所有advisors,并且执行相应判断逻辑来决定相应拦截器是否适用,最后得到代理方法的拦截器集合
具体代码逻辑如下

AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
for (Advisor advisor : config.getAdvisors()) {
    if (advisor instanceof PointcutAdvisor) {
        // Add it conditionally.
        PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
        if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
            MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
            MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
            if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
                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));
    }
}

注意到获取advisor的拦截器使用了registry.getInterceptors(advisor),在DefaultAdvisorChainFactory中获取Adivisor里面的拦截器这个功能委托给了AdvisorAdapterRegistry来实现

AdvisorAdapterRegistry接口定义如下

public interface AdvisorAdapterRegistry {

    Advisor wrap(Object advice) throws UnknownAdviceTypeException;

    MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException;

    void registerAdvisorAdapter(AdvisorAdapter adapter);
}

其中getInterceptors方法实现如下

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));
        }
    }
    if (interceptors.isEmpty()) {
        throw new UnknownAdviceTypeException(advisor.getAdvice());
    }
    return interceptors.toArray(new MethodInterceptor[interceptors.size()]);
}

在这个方法里面主要通过AdvisorAdapter 来把Advisor里面的Adivce(通知)转换为对应的拦截器
AdvisorAdapter接口定义如下

public interface AdvisorAdapter {

    boolean supportsAdvice(Advice advice);

    MethodInterceptor getInterceptor(Advisor advisor);

}

在DefaultAdvisorAdapterRegistry中默认注册了3个Adapter

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

注意到并没有环绕通知,因为环绕通知直接采用实现MethodInteceptor来做
在getInterceptors方法里面

if (advice instanceof MethodInterceptor) {
    interceptors.add((MethodInterceptor) advice);
}

这句代码就是为了给环绕通知做处理
看下AdvisorAdapter和对应拦截器的具体实现能让我们理解更加深刻,我们来看下MethodBeforeAdviceAdapter和MethodBeforeAdviceInterceptor

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, Serializable {

    private MethodBeforeAdvice advice;


    /**
     * Create a new MethodBeforeAdviceInterceptor for the given advice.
     * @param advice the MethodBeforeAdvice to wrap
     */
    public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
        Assert.notNull(advice, "Advice must not be null");
        this.advice = advice;
    }

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

拦截器的作用主要是封装advice里的逻辑,并且实现链式调用

总结一下,在这里我们把代理中比较重要的拦截器链式调用如何实现讲清楚,接下来只要关注怎么生成代理对象,以及在代理对象中怎么调用拦截器链

相关文章

  • 2.SpringAop之AdvisedSupport

    1.类继承结构 2.解析 AdvisedSupport继承ProxyConfig,自身提供了以下功能 配置当前代理...

  • 3.SpringAop之ProxyCreatorSupport

    1.类继承关系 2.解析 ProxyCreatorSupport继承AdvisedSupport,在此基础上提供了...

  • 十之

    博学之,审问之,慎思之,明辨之,笃行之。 励志之,健身之,涅槃之,弘毅之,自强之!

  • 读记|唐诗人:诗心煎红尘(二)

    愈之挫之 险之退之 借之济之 忠之犯之 勇之夺之 衰之立之 坚之韧之 载之言之 一代宗师 成之传之 字曰子厚 道解...

  • 《寄君归》

    思之念之 见之不忘 吾亦求之 求之不得 吾亦念之 兮之盼之 来之归之 欲予离之 得之兮之 心思念之 盼来归之 归之...

  • 飘零

    艾雪儿 难耐心中怦然之 抑之,控之,思之,忘之 能否任之,弃之,拥之,念之 山河为鉴 赴之,游之,悦之,相守之…

  • 《美》

    刚之美,软之美,善之美,心之美。 水之美,声之美,爱之美,景之美,笑之美,物之美,月之美。 仁之美,慈之美,德之美...

  • 众说纷云

    众说纷云 文‖曾之一 20200220 古人说 真之假之善之恶之美之丑之 今人说 真之假之善之恶之美之丑之 后人说...

  • 安沨

    博学之,审问之,慎思之,明辨之,笃行之。

  • 2019-01-13

    博学之、明辨之、慎思之、审问之、笃行之

网友评论

    本文标题:2.SpringAop之AdvisedSupport

    本文链接:https://www.haomeiwen.com/subject/ozreaxtx.html