Spring源碼解析-Advice中的Adapter模式

在spring中與通知相關的類有:spring

       以Advice結尾的通知接口ide

     MethodBeforeAdvice    AfterReturningAdvice   ThrowsAdvicethis

      以Interceptor結尾的攔截器spa

          MethodBeforeAdviceInterceptor   AfterReturningAdviceInterceptor   ThrowsAdviceInterceptorcode

     以Adapter結尾的適配器blog

           MethodBeforeAdviceAdapter   AfterReturningAdviceAdapter  ThrowsAdviceAdapter接口

     先了解一下Adapter模式get

     

     而這三者間的關係以MethodBefore爲例:源碼

     

下面以MethodBefore爲例,看一下源碼。io

先看一下AdvisorAdapter接口

public interface AdvisorAdapter {

    boolean supportsAdvice(Advice advice);

    
    MethodInterceptor getInterceptor(Advisor advisor);

}

MethodBeforeAdviceAdapter類

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);
    }

}

而MethodBeforeAdviceInterceptor是具體的實現。

例外在看一下MethodBeforeAdviceInterceptor類

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();
    }

}

實現了MethodIntercepter接口,在調用invoke進行攔截的時候,是先調用before方法裏面,而後在調用具體的方法實現。

相關文章
相關標籤/搜索