Getting multiple guice singletons of the same type

两盒软妹~` 提交于 2019-11-30 11:49:52

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) { ... }

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.


Note that it also works when you want to bind multiple singletons of the same type:

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

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!