【问题标题】:How to define order of method interceptors in Guice?如何在 Guice 中定义方法拦截器的顺序?
【发布时间】:2012-01-08 15:24:03
【问题描述】:

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

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

【问题讨论】:

    标签: methods aop guice interceptor


    【解决方案1】:

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

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

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

    retryInterceptor 将在transactionalInterceptor 之前执行。

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

    【讨论】:

    • 这是一种非常有限的方法。如果你有一个模块设置了一些拦截器,你需要安装这个模块,并在模块安装的拦截器之间配置一个额外的拦截器,没有办法。
    • @BrunoJCM 有一种方法可以使用Guice SPI 及其访问者重新排序它们,您可以从模块中获取所有拦截器绑定的列表,重新排序它们,然后使用这些新元素创建一个模块。我做了类似的事情来使用 Order 注释对多绑定器绑定进行排序。
    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2012-02-01
    相关资源
    最近更新 更多