如何在 Guice 中定义方法拦截器的顺序?

发布于 2024-12-18 13:05:03 字数 220 浏览 3 评论 0原文

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

在 Spring 中,您可以使用拦截器的 Ordered 接口来确保事务拦截器在重试拦截器内执行。有没有办法在 Guice 中达到同样的效果?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

内心旳酸楚 2024-12-25 13:05:03

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

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

或者

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

retryInterceptor 将在 transactionalInterceptor 之前执行。

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

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);

or

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

the retryInterceptor will be executed before the 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文