【问题标题】:How can we bind method interceptors requiring assisted injection in guice?我们如何在 guice 中绑定需要辅助注入的方法拦截器?
【发布时间】:2012-11-16 06:42:54
【问题描述】:

我有一个使用辅助注入创建的类 (WindowedCounter)。我需要将此类的工厂注入到方法拦截器中。现在方法拦截器只能绑定到具体实例。所以我的问题是如何巧妙地做到这一点。

下面的代码是我到目前为止想出的。我为工厂创建了一个工厂提供程序,并使用它在模块本身中获取工厂实例。然后将其绑定到两个类并用于获取绑定到拦截器的实例。但是,从 Guice 3.0 开始,FactoryProvider 类已被贬低。

Guice 3.0 的做法是什么?

我可以在模块中注入实例吗?

Provider<WindowedCounterFactory> wCountFactoryProvider = FactoryProvider.newFactory(WindowedCounterFactory.class, WindowedCounter.class);

bind(WindowedCounterFactory.class).toProvider(wCountFactoryProvider);

WindowedCounterFactory wCountFactory = wCountFactoryProvider.get();

bindInterceptor(Matchers.any(), Matchers.annotatedWith(RateLimited.class), new RateLimitingInterceptor(wCountFactory));

【问题讨论】:

    标签: guice guice-3


    【解决方案1】:

    FactoryProvider 的替换是FactoryModuleBuilder。相反,它会将一个模块返回给install,但在您的模块中,您可以调用getProvider 来为您的类型获取一个有效的注入器创建提供程序。

    理论上,在创建 Injector 之前,您不应该访问您的类型(例如,某些依赖项可能绑定在其他模块中);这可能需要您重构以在 MethodInterceptor 中使用 Provider,或将拦截器安装在 child injector 中,以便您可以从“父”注入器获取工厂实例。

    install(new FactoryModuleBuilder().build(WindowedCounterFactory.class));
    bindInterceptor(Matchers.any(), Matchers.annotatedWith(RateLimited.class),
        new RateLimitingInterceptor(getProvider(WindowedCounterFactory.class)));
    

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 2012-11-04
      • 2012-02-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      相关资源
      最近更新 更多