跳到主要内容

自定义建议类

QWen Plus 中英对照 Custom Advice Classes

除了提供的建议类 如前所述,你还可以实现自己的建议类。虽然你可以提供 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;
java

回调参数是为了避免子类直接处理 AOP 而提供的便利。调用 callback.execute() 方法会调用消息处理器。

target 参数为那些需要为特定处理程序维护状态的子类提供支持,也许可以通过在以 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;
}
}
java
备注

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

有关更多信息,请参阅 ReflectiveMethodInvocation Javadoc。