自定义建议类
除了前面描述的提供的建议类之外,您还可以实现自己的建议类。
虽然您可以提供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()
method 调用消息处理程序。
这target
参数是为那些需要维护特定处理程序的状态的子类提供的,可能是通过在Map
keyed by 目标。
此功能允许将相同的建议应用于多个处理程序。
这RequestHandlerCircuitBreakerAdvice
使用 advice this 来保持每个处理程序的 Circuit breaker 状态。
这message
parameter 是发送到处理程序的消息。
虽然 advice 无法在调用处理程序之前修改消息,但它可以修改有效负载(如果它具有可变属性)。
通常,通知会使用该消息进行日志记录,或者在调用处理程序之前或之后的某个位置发送消息的副本。
返回值通常是由callback.execute()
.
但是,该建议确实能够修改返回值。
请注意,只有AbstractReplyProducingMessageHandler
instances 返回值。
以下示例显示了一个自定义通知类,该类扩展了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。 |