除了前面介绍的已提供的建议类外,您还可以实施自己的建议类。
虽然您可以提供 (通常) 的任何实现,但我们通常建议您将 子类 .
这样做的好处是避免了编写低级面向方面的编程代码,并提供了一个专门为在此环境中使用而定制的起点。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;
}
}
除了该方法之外,还提供了一种附加方法:。
此方法必须用于在 的单次执行中可能多次调用调用的情况,例如在 .
这是必需的,因为 Spring AOP 对象通过跟踪上次调用链中的哪个建议来维护状态。
必须为每次调用重置此状态。 有关更多信息,请参见 ReflectiveMethodInvocation Javadoc。 |
除了该方法之外,还提供了一种附加方法:。
此方法必须用于在 的单次执行中可能多次调用调用的情况,例如在 .
这是必需的,因为 Spring AOP 对象通过跟踪上次调用链中的哪个建议来维护状态。
必须为每次调用重置此状态。 有关更多信息,请参见 ReflectiveMethodInvocation Javadoc。 |