如需使用最新稳定版本,请使用 Spring Integration 7.0.4spring-doc.cadn.net.cn

自定义通知类

除了前面描述的 通知类 之外,您还可以实现自己的通知类。 虽然您可以提供 org.aopalliance.aop.Advice(通常是 org.aopalliance.intercept.MethodInterceptor)的任何实现,但我们通常建议您继承 o.s.i.handler.advice.AbstractRequestHandlerAdvice。 这样做的好处是避免了编写底层面向切面编程代码,同时提供了一个专门针对此环境设计的起点。spring-doc.cadn.net.cn

子类需要实现 doInvoke() 方法,其定义如下:spring-doc.cadn.net.cn

/**
 * 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() 方法将触发消息处理器。spring-doc.cadn.net.cn

为那些需要为特定处理器维护状态的子类提供了 target 参数,或许是通过以目标为键的 Map 来维护该状态。 此功能允许将相同的通知应用于多个处理器。 RequestHandlerCircuitBreakerAdvice 使用此通知来为每个处理器保持熔断器状态。spring-doc.cadn.net.cn

message 参数是发送给处理器的消息。 虽然通知无法在调用处理器之前修改消息,但它可以修改有效载荷(如果它具有可变属性)。 通常,通知会使用此消息进行日志记录,或在调用处理器之前或之后将消息的副本发送到某处。spring-doc.cadn.net.cn

返回值通常由 callback.execute() 返回的值决定。 然而,通知(advice)确实具备修改返回值的能力。 请注意,只有 AbstractReplyProducingMessageHandler 实例会返回值。 以下示例展示了一个扩展自 AbstractRequestHandlerAdvice 的自定义通知类:spring-doc.cadn.net.cn

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 对象通过跟踪链中最后被调用的通知来维护状态。 每次调用都必须重置此状态。spring-doc.cadn.net.cn

有关更多信息,请参阅 ReflectiveMethodInvocation Javadoc。spring-doc.cadn.net.cn