如何在Guice中定义方法拦截器的顺序? [英] How to define order of method interceptors in 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屋!