miljanm
miljanm

Reputation: 936

Guice: Creating more than one object instance with different configurations

I would like to know what is the best practice for the following problem:

I want have 2 instances of some class (BlockingQueue in particular) to inject them into my other classes. Each of these instances is configured separately (in particular, they have different capacities) and they don't support automatic injection via @Inject annotation. The 2 instances are the only 2 instances of that class in the application.

Now, I know that I can use binding annotations to distinguish between the two instances and use instance binding to actually bind to a single instance. But the problem is that I also need to configure these two objects and I want to obtain configuration dependencies from Guice. What do you think would be a best way to do this?

Upvotes: 0

Views: 1851

Answers (1)

eiden
eiden

Reputation: 2349

One option is to use @Provides bindings

Create a method in your guice module that provides the dependency. You can add dependencies you need to construct the object in the method signature.

@Provides
@MyBindingAnnotation
@Singleton
BlockingQueue<String> provideBlockingQueue(MyGuiceManagedConfig config){
    return new LinkedBlockingQueue<String>(config.getCapacity());
}

...and they don't support automatic injection via @Inject annotation

By the way, Guice has a feature called constructor bindings, which makes it possible to bind constructors without @Inject:

try {
    binder().bind(Integer.TYPE).toInstance(10);

    binder().bind(new TypeLiteral<BlockingQueue<String>>() {})
        .toConstructor(LinkedBlockingQueue.class.getConstructor(Integer.TYPE));
} catch (NoSuchMethodException e) {
    addError(e);
}

Upvotes: 1

Related Questions