问题
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