Reputation: 15492
I'm new to Guice and I'm not sure I understand the difference between
1) untargeted bind - when do I need to use this?
bind(Logger.class);
2 )'toInstance()` bind - how do I init an object that has ctor with dependencies? or is it for data object with no dependencies only?
bind(Logger.class).toInstance(new Logger(..?..));
3) not writing any bind in the
@Override
protected void configure() {
}
what happens in any of the above when I run
and when should I choose any of them?
Upvotes: 3
Views: 2508
Reputation: 12932
bind(Untargetted.class).in(Scopes.SINGLETON);
, for example)PrivateModule
toInstance()
for objects with constructor dependencies. It's more useful for non-Guicey objects like data objects or library classes you have to create with new
.Module
, Guice creates a just-in-time binding for it. The behaviour is almost identical to bind(Untargetted.class);
The major difference between untargetted and toInstance()
bindings is that toInstance()
bindings will be singletons ("obviously" -- there's only one instance!), but untargetted bindings, like most other bindings, have no scope by default. So if different classes inject an Untargetted
, they'll get different instances unless you put a scope on it.
Another difference is that when you don't use toInstance()
, Guice creates the instance for you, enabling things like aspect-oriented programming.
Generally, you should prefer not to use toInstance()
bindings unless you have to. Untargetted bindings have the advantage of being more explicit, but it can be verbose to list them all, so just-in-time bindings are often used instead. Especially in cases like this:
bind(Interface.class)
.to(Implementation.class);
// Technically, Guice creates a just-in-time binding for Implementation here
Upvotes: 5