自訂建議類別

除了先前描述的提供的建議類別之外,您可以實作自己的建議類別。雖然您可以提供 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 參數是為需要為特定處理器維護狀態的那些子類別提供的,可能是透過在以目標為鍵的 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。