I have a question: Usually in Guice I use bind(classe).to(another_class_Implementation) ...
However I found in a code source that they have used bind(class) only ( without the part ".to(another_class_Implementation)" ) ...
What does this mean ( bind(class) without "to or as" ) ?
Here is the part of code in question:
public class RestModule extends AbstractModule {
@Override
protected void configure() {
bind(RootResource.class);
bind(DeveloperUtilsRedirector.class);
bind(M34Repository.class).to(M34RepositoryImpl.class);
bind(IGARepository.class).to(IGARepositoryImpl.class);
Answers are appreciated
A bind
statement without a to
is called an Untargeted Binding (misspelled as "Untargetted Bindings" in the wiki URL) in the Guice docs. From that wiki page:
You may create bindings without specifying a target. This is most useful for concrete classes and types annotated by either
@ImplementedBy
or@ProvidedBy
. An untargetted [sic] binding informs the injector about a type, so it may prepare dependencies eagerly.
You'll see this in Guice for three purposes:
Slight performance improvement via eager loading.
When Guice encounters a dependency that it doesn't have a binding for (say, class A), it inspects the class to see if it can be injected via an @Inject
-annotated or zero-arg public constructor. If so, Guice creates a Just-In-Time binding (or "implicit binding"). This is done through reflection, and may cause a cascade of other bindings (requesting A inspects A, then A's dependency B, then B's dependency C, and so forth), which can cause some runtime slowdown.
By pre-emptively making an untargeted binding, you inform Guice about an injectable class, which allow it to pay that reflection cost at startup for more predictable performance.
Guice will throw an exception if it cannot create the object you inject, but in the case of @ImplementedBy or @ProvidedBy (or getInstance
or injectMembers
) Guice will not fail if it hasn't inspected the class with the missing binding yet. By listing classes you use, Guice will pre-analyze those objects as in (1), but will also recognize at app startup that a binding is missing. This may be handy during development, especially if you are injecting an object with getInstance
or injectMembers
long after application startup; you might prefer that failure to happen immediately.
Though implicit bindings are enabled by default, they can be disabled through requireExplicitBindings
. This means that any injected classes need to have associated bindings, including classes with eligible constructors. An untargeted binding would resolve that situation easily.