-
Notifications
You must be signed in to change notification settings - Fork 113
Modules & Bindings
Modules define bindings.
The class toothpick.config.Module defines a small DSL to conveniently express bindings, and bindings can be expressed in various ways :
class SimpleModule extends Module {
SimpleModule() {
bind(IFoo.class).to(Foo.class); // case 1
bind(IFoo.class).to(new Foo()); // case 2
bind(IFoo.class).toProvider(FooProvider.class); // case 3
bind(IFoo.class).toProvider(new FooProvider()); // case 4
bind(Foo.class); // case 5
}
}
The various binding modes are :
- case 1: Every
@Inject IFoowill be assigned a new instance ofFoo. - case 2: Every
@Inject IFoowill be assigned the same instance ofFoo. The instance defined in the module. - case 3: Every
@Inject IFoowill be assigned a new instance ofFooproduced by a new instance ofFooProvider. - case 4: Every
@Inject IFoowill be assigned a new instance ofFooproduced by the same instance ofFooProvider. The instance defined in the module. - case 5 : Every
@Inject Foowill be assigned a new instance ofFoo.
In the example above, in the cases 1, 3 and 5, ToothPick is responsible for creating the instances during injection. Whereas in cases 2 and 4, the developer herself is creating the instances of Foo, either directly or via a provider that she defines.
A good rule to remember is :
As soon as ToothPick creates an object, it will be injected.
which also implies that :
As soon as a developer creates an object with ToothPick, the developer has to take care of injecting this object dependencies.
This means that if we define the class :
class Foo {
@Inject Scope s;
}
In the cases 1, 3 and 5, all instances of Foo that are created during injection by ToothPick will themselves be injected. All injected methods and fields will be called/assigned and their annotated constructor or the default constructor will be used to create the instances of Foo.
In the case 2 and 4, the developer will have to assign the field s to a scope, the developer can do it manually or by asking ToothPick to do it : ToothPick.inject( foo, s ).