Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 587
Elad Benda2 Avatar asked Dec 06 '25 09:12

Elad Benda2


1 Answers

  1. Untargetted bindings: you rarely need to use them, but they're necessary if
    • You want to specify a scope (bind(Untargetted.class).in(Scopes.SINGLETON);, for example)
    • You want to keep the binding inside a PrivateModule
    • You have required explicit bindings
  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
like image 139
Tavian Barnes Avatar answered Dec 07 '25 21:12

Tavian Barnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!