如何在 Guice 中定义方法拦截器的顺序? [英] How to define order of method interceptors in Guice?

查看:36
本文介绍了如何在 Guice 中定义方法拦截器的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时需要知道 Guice 中拦截方法调用的方法拦截器的顺序.一个简单的示例场景是将 guice-persist 提供的 @Transactional 方法拦截器与自定义 @Retry 方法拦截器一起使用.重试拦截器必须在事务拦截器之外运行,以确保重试不在同一事务中执行.

Sometimes there's a need to know the order of method interceptors that intercept a method call in Guice. A simple example scenario would be to use guice-persist provided @Transactional method interceptor with a custom @Retry method interceptor. The retry interceptor must be run outside of the transactional interceptor to make sure the retries are not executed within the same transaction.

在 Spring 中,您可以使用拦截器的 Ordered 接口来确保事务拦截器在重试拦截器中执行.有没有办法在 Guice 中实现相同的目标?

In Spring you could use the Ordered interface for the interceptor to make sure the transaction interceptor is executed within the retry interceptor. Is there a way to achieve the same in Guice?

推荐答案

Guice 按照拦截器注册的顺序调用拦截器.因此,如果您像这样定义它们:

Guice invokes the interceptors in the order in which they were registered. So if you define them something like this:

bindInterceptor(any(), annotatedWith(Retry.class), retryInterceptor);
bindInterceptor(any(), annotatedWith(Transactional.class), transactionalInterceptor);

bindInterceptor(any(), annotatedWith(Retry.class), retryInterceptor, transactionalInterceptor);

retryInterceptor 将在 transactionalInterceptor 之前执行.

如果您有多个模块,同样适用 - 第一个模块的拦截器在第二个模块的拦截器之前执行,依此类推.

Same applies if you have multiple modules - the interceptors from first module are executed before the interceptors of the seconds module and so on.

这篇关于如何在 Guice 中定义方法拦截器的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆