有时需要知道在 Guice 中拦截方法调用的方法拦截器的顺序。一个简单的示例场景是使用 guice-persist 提供的 @Transactional 方法拦截器和自定义 @Retry 方法拦截器。重试拦截器必须在事务拦截器之外运行,以确保重试不在同一个事务中执行。
在 Spring 中,您可以使用拦截器的 Ordered 接口(interface)来确保事务拦截器在重试拦截器中执行。有没有办法在 Guice 中实现同样的效果?
最佳答案
Guice 按照它们注册的顺序调用拦截器。因此,如果您将它们定义如下:
bindInterceptor(any(), annotatedWith(Retry.class), retryInterceptor);
bindInterceptor(any(), annotatedWith(Transactional.class), transactionalInterceptor);
或者
bindInterceptor(any(), annotatedWith(Retry.class), retryInterceptor, transactionalInterceptor);
retryInterceptor
将在 transactionalInterceptor
之前执行.如果您有多个模块,同样适用 - 第一个模块的拦截器在第二个模块的拦截器之前执行,依此类推。
关于methods - 如何在 Guice 中定义方法拦截器的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8308203/