Elad Benda2
Elad Benda2

Reputation: 15492

untargeted bind vs. `toInstance()` bind

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

Answers (1)

Tavian Barnes
Tavian Barnes

Reputation: 12932

  1. Untargetted bindings: you rarely need to use them, but they're necessary if
  2. You're right, generally you can't use 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.
  3. When you inject a type that is not bound in any 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

Related Questions