|
如需使用最新稳定版本,请使用 Spring Integration 7.0.4! |
自定义通知类
除了前面描述的 通知类 之外,您还可以实现自己的通知类。
虽然您可以提供 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() 返回的值决定。
然而,通知(advice)确实具备修改返回值的能力。
请注意,只有 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。 |