自定义通知类

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

除了 execute() 方法之外,ExecutionCallback 还提供了一个额外的方法:cloneAndExecute()。 在 doInvoke() 的单个执行中可能多次调用调用的情况下,例如在 RequestHandlerRetryAdvice 中,必须使用此方法。 这是必需的,因为 Spring AOP org.springframework.aop.framework.ReflectiveMethodInvocation 对象通过跟踪链中上次调用的通知来维护状态。 每次调用都必须重置此状态。 有关更多信息,请参阅 ReflectiveMethodInvocation Javadoc。