Reputation: 1247
I am relatively new to Guice, so this may be basic question. It looks like Guice has the option to require explicit bindings. Is there any clear advantage to requiring explicit bindings? Does anyone regularly use this option in practice?
Upvotes: 3
Views: 4952
Reputation: 2840
I recently sat through a 1-hour debugging session because we didn't use this config. The problem was that multiple instances were created when I expected a singleton by default. Forcing an explicit binding is a good reminder to think about whether it should be a singleton or not.
Upvotes: 2
Reputation: 227
I too spent few hours in debugging. The reason was that I forgot to add a binding of a concrete class to singleton scope. In order to have explicit bindings always, I used one answer from How do you prevent Guice from injecting a class not bound in the Module? (not the current chosen one): binder().requireExplicitBindings();
(in the configure method of AbstractModule).
Upvotes: 0
Reputation: 91
We use this option in practice. We use Guice only to wire our application together, not for any sort of per-request object construction. As a result, most of our bindings are in Singleton scope - we want, for example, our business logic and statistics interfaces to both work off the same persistence layer object.
In the absence of an explicit binding, Guice will attempt to satisfy the injection point using a JIT binding. This binding will be done in the "no scope" scope, which provides a fresh object instance to each injection point. That's almost never what we want, and leads to bizarre runtime errors. Forcing explicit bindings forces people to think about, and enumerate, the scope of each of their bindings.
Upvotes: 6