views:

676

answers:

2

can you get 2 singleton instances of the same underlying type?

this is obviously trivial in spring as it is based on named instances to which you attach a scope but I can't see the equivalent in guice which is about binding types to implementation classes. Note that I don't want to have to bind to the instance as the instances in question are injected with other dependencies by guice.

+4  A: 

It's easy in Guice too! Create two biding annotations, say @One and @Two and then

bind(MySingleton.class).annotatedWith(One.class).toInstance(new MySingleton());
bind(MySingleton.class).annotatedWith(Two.class).toInstance(new MySingleton());

and then

@Inject
public SomethingThatDependsOnSingletons(@One MySingleton s1,
    @Two MySingleton t2) { ... }
Marcin
Matt
You don't need to bind it to an instance. Two different annotations to the same class, in scope singleton, will create two separate instances already.
kRON
+3  A: 

I'd like to complement Marcin's response, by adding that you don't have to limit yourself to using toInstance() or provider methods in such a situation.

The following will work just as well:

bind(Person.class).annotatedWith(Driver.class).to(MartyMcFly.class).in(Singleton.class);
bind(Person.class).annotatedWith(Inventor.class).to(DocBrown.class).in(Singleton.class);

[...]

@Inject
public BackToTheFuture(@Driver Person marty, @Inventor Person doc) { ... }

Guice will inject the dependencies as usual when instantiating the MartyMcFly and DocBrown classes.

Edit: The sample code I give as an example comes from a Guice Grapher Test. Looking at the Guice tests is a great way to better understand how to use the API (which also applies to every project with good unit tests).

eneveu
I love the example
Jesse Wilson
Thanks Jesse :) The sample code I used to illustrate my point actually comes from a test for the Guice Grapher extension. I thought it was funny and pasted it as-is. I should have put a link to the source, though (I'll do that right now). As an aside, I love your blog and especially your practical articles on Guice / Google Collections ( http://publicobject.com/ ). We need more blogs like yours. So, thanks for this, too.
eneveu