what's the difference between these two binding declarations with Google Guice?

岁酱吖の 提交于 2020-01-04 09:54:39

问题


What's the difference between

bind(FooImpl.class).in(Scopes.SINGLETON);
bind(Foo.class).to(FooImpl.class);

and

bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);

With Google Guice?

edit:

The second declaration create two instances on Singleton in a project I am working on. Reference here


回答1:


In reference to Google Guice documentation:

In linked bindings, scopes apply to the binding source, not the binding target. Suppose we have a class Applebees that implements both Bar and Grill interfaces. These bindings allow for two instances of that type, one for Bars and another for Grills:

bind(Bar.class).to(Applebees.class).in(Singleton.class);
bind(Grill.class).to(Applebees.class).in(Singleton.class);

This is because the scopes apply to the bound type (Bar, Grill), not the type that satisfies that binding (Applebees). To allow only a single instance to be created, use a @Singleton annotation on the declaration for that class. Or add another binding:

bind(Applebees.class).in(Singleton.class);

So, It's possible to have two instances of FooImpl in the second way but not with the first way of writing the binding.




回答2:


There is no difference. Both will bind Foo to an instance of FooImpl in the SINGLETON scope.



来源:https://stackoverflow.com/questions/11002935/whats-the-difference-between-these-two-binding-declarations-with-google-guice

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