Domanda

I have a class (WindowedCounter) which is creating using assisted injection. I need to inject a factory for this class into a method interceptor. Now a method interceptor can only be bound to a concrete instance. So my question is how to do this neatly.

The code below is what I came up with so far. I create a Factory Provider for the factory and use it to get a factory instance in the module itself. Which is then bound to both the class and used to get an instance to bind to the interceptor. However FactoryProvider class is depreciated as of Guice 3.0.

What is the Guice 3.0 way of doing this?

Can I inject instances in a module?

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));
È stato utile?

Soluzione

The replacement for FactoryProvider is FactoryModuleBuilder. It will return a Module to install, instead, but in your Module you can call getProvider to get a valid-at-Injector-creation Provider for your type.

In theory you should not want to access your types until the Injector is created (as some dependencies might be bound in other modules, for instance); this may require you to refactor to use a Provider in your MethodInterceptor, or install your interceptor in a child injector so you can get an instance of your Factory from a "parent" injector.

install(new FactoryModuleBuilder().build(WindowedCounterFactory.class));
bindInterceptor(Matchers.any(), Matchers.annotatedWith(RateLimited.class),
    new RateLimitingInterceptor(getProvider(WindowedCounterFactory.class)));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top