Advised Handler Properties

有时,从建议中访问句柄属性很有用。例如,大多数句柄实现 NamedComponent 允许你访问组件名称。

Sometimes, it is useful to access handler properties from within the advice. For example, most handlers implement NamedComponent to let you access the component name.

可以通过 target 参数(在子类化 AbstractRequestHandlerAdvice 时)或 invocation.getThis()(在实现 org.aopalliance.intercept.MethodInterceptor 时)访问目标对象。

The target object can be accessed through the target argument (when subclassing AbstractRequestHandlerAdvice) or invocation.getThis() (when implementing org.aopalliance.intercept.MethodInterceptor).

当对整个句柄提供建议(例如,当句柄不产生回复或建议实现 HandleMessageAdvice 时),你可以将目标对象强制转换为接口,例如 NamedComponent,如下面的例子所示:

When the entire handler is advised (such as when the handler does not produce replies or the advice implements HandleMessageAdvice), you can cast the target object to an interface, such as NamedComponent, as shown in the following example:

String componentName = ((NamedComponent) target).getComponentName();

当你直接实现 MethodInterceptor 时,可以将目标对象强制转换为如下所示:

When you implement MethodInterceptor directly, you could cast the target object as follows:

String componentName = ((NamedComponent) invocation.getThis()).getComponentName();

当仅建议 handleRequestMessage() 方法(在生成回复的句柄中)时,你需要访问完整的句柄,它是一个 AbstractReplyProducingMessageHandler。以下示例显示了如何执行此操作:

When only the handleRequestMessage() method is advised (in a reply-producing handler), you need to access the full handler, which is an AbstractReplyProducingMessageHandler. The following example shows how to do so:

AbstractReplyProducingMessageHandler handler =
    ((AbstractReplyProducingMessageHandler.RequestHandler) target).getAdvisedHandler();

String componentName = handler.getComponentName();