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.
It's easy in Guice too! Create two biding annotations, say
@One
and@Two
and thenand then
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:
[...]
Guice will inject the dependencies as usual when instantiating the MartyMcFly and DocBrown classes.
Note that it also works when you want to bind multiple singletons of the same type:
For this to work, you must make sure that
Person
is not bound in the Singleton scope, either explicitely in the Guice module, or with the@Singleton
annotation. More details in this Gist.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).