此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Integration 6.4.3spring-doc.cadn.net.cn

自定义建议类

除了前面描述的提供的 advice 类之外,您还可以实现自己的 advice 类。 虽然您可以提供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;

callback 参数可以方便地避免直接处理 AOP 的子类。 调用callback.execute()method 调用消息处理程序。spring-doc.cadn.net.cn

target参数是为那些需要维护特定处理程序的状态的子类提供的,可能是通过在Mapkeyed by 目标。 此功能允许将相同的建议应用于多个处理程序。 这RequestHandlerCircuitBreakerAdvice使用 advice this 来保持每个处理程序的 Circuit breaker 状态。spring-doc.cadn.net.cn

messageparameter 是发送到处理程序的消息。 虽然 advice 无法在调用处理程序之前修改消息,但它可以修改有效负载(如果它具有可变属性)。 通常,通知会使用该消息进行日志记录,或者在调用处理程序之前或之后的某个位置发送消息的副本。spring-doc.cadn.net.cn

返回值通常是由callback.execute(). 但是,该建议确实能够修改返回值。 请注意,只有AbstractReplyProducingMessageHandlerinstances 返回值。 以下示例显示了一个自定义通知类,该类扩展了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 AOPorg.springframework.aop.framework.ReflectiveMethodInvocationObject 通过跟踪链中的哪个通知上次被调用来维护状态。 必须为每个调用重置此状态。spring-doc.cadn.net.cn

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