自定義通知類

除了之前描述的提供的通知類之外,您還可以實現自己的通知類。雖然您可以提供 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;

callback 引數是一個便利手段,可以避免子類直接處理 AOP。呼叫 callback.execute() 方法會呼叫訊息處理器。

target 引數是為那些需要為特定處理器維護狀態的子類提供的,或許可以透過將狀態儲存在以 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。