自定義 Advice 類

除了前面描述的提供的通知類之外,您還可以實現自己的通知類。雖然您可以提供任何 org.aopalliance.aop.Advice 的實現(通常是 org.aopalliance.intercept.MethodInterceptor),但我們通常建議您繼承 o.s.i.handler.advice.AbstractRequestHandlerAdvice。這樣做的好處是避免編寫低階的面向切面程式設計程式碼,並提供一個專門為在此環境中使用而量身定製的起點。

子類需要實現 doInvoke() 方法,其定義如下:

/**
 * Subclasses implement this method to apply behavior to the {@link MessageHandler} callback.execute()
 * invokes the handler method and returns its result, or null).
 * @param callback Subclasses invoke the execute() method on this interface to invoke the handler method.
 * @param target The target handler.
 * @param message The message that will be sent to the handler.
 * @return the result after invoking the {@link MessageHandler}.
 * @throws Exception
 */
protected abstract Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception;

回撥引數是為了方便,避免子類直接處理 AOP。呼叫 callback.execute() 方法會呼叫訊息處理器。

target 引數是為那些需要為特定處理程式維護狀態的子類提供的,可能透過在以目標為鍵的 Map 中維護該狀態。此功能允許將相同的通知應用於多個處理程式。RequestHandlerCircuitBreakerAdvice 使用此通知來為每個處理程式維護斷路器狀態。

message 引數是傳送給處理器的訊息。雖然通知不能在呼叫處理器之前修改訊息,但它可以修改載荷(如果它具有可變屬性)。通常,通知會在呼叫處理器之前或之後使用訊息進行日誌記錄或將訊息副本傳送到其他地方。

返回值通常是 callback.execute() 返回的值。但是,通知確實能夠修改返回值。請注意,只有 AbstractReplyProducingMessageHandler 例項才返回值。以下示例顯示了一個擴充套件 AbstractRequestHandlerAdvice 的自定義通知類:

public class MyAdvice extends AbstractRequestHandlerAdvice {

    @Override
    protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
        // add code before the invocation
        Object result = callback.execute();
        // add code after the invocation
        return result;
    }
}

除了 execute() 方法之外,ExecutionCallback 還提供了一個額外的方法:cloneAndExecute()。在 doInvoke() 的單次執行中可能多次呼叫呼叫的情況下,例如在 RequestHandlerRetryAdvice 中,必須使用此方法。這是必需的,因為 Spring AOP 的 org.springframework.aop.framework.ReflectiveMethodInvocation 物件透過跟蹤鏈中最後呼叫的通知來維護狀態。每次呼叫都必須重置此狀態。

有關更多資訊,請參閱 ReflectiveMethodInvocation Javadoc。

© . This site is unofficial and not affiliated with VMware.