カスタムアドバイスクラス
前述の提供されたアドバイスクラスに加えて、独自のアドバイスクラスを実装できます。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;
}
}
詳細については、ReflectiveMethodInvocation (Javadoc) Javadoc を参照してください。 |