Injecting instances
In this tutorial we will inject instances into classes. We will use 2 approaches:
- Using an
InstanceInjector
- Adding a class that will have its fields injected to the bindings graph
Modules
We will define two independent modules: one will provide the String
message and the other will provide the int
id.
public class MessageModule extends AbstractModule {
@Provides
String message() {
return "hello";
}
}
public class IdModule extends AbstractModule {
@Provides
int id() {
return 123;
}
}
Using an InstanceInjector
Here is the class whose fields must be injected.
public class Injected {
@Inject
String value;
@Inject
int id;
}
We need to create an Injector
and pass MessageModule
and IdModule
as parameters.
We also need to add a binding for the instance injector. To do this, we will use a ModuleBuilder
to manually create a third module whose sole purpose will be to bind the instance injector.
Injector injector = Injector.of(
new MessageModule(),
new IdModule(),
ModuleBuilder.create()
.bindInstanceInjector(Injected.class)
.build());
Finally, we need to obtain the InstanceInjector
from the Injector and use it to inject the fields into the newly created Injected
instance.
InstanceInjector<Injected> instanceInjector = injector.getInstanceInjector(Injected.class);
Injected injected = new Injected();
instanceInjector.injectInto(injected);
Adding class to bindings graph
Here again the class whose fields are to be injected is represented. Note that this time there is an @Inject
annotation annotating the type.
@Inject
public class Injected {
@Inject
String value;
@Inject
int id;
}
Alternatively, you can add a constructor and annotate it with the @Inject
annotation, as shown below:
public class Injected {
private final String value;
private final int id;
@Inject
public Injected(String value, int id) {
this.value = value;
this.id = id;
}
//...
}
We still need to create an Injector
and pass MessageModule
and IdModule
as parameters.
However, instead of binding the instance injector, this time we will bind the Injected
class. To do this, we will also use a
ModuleBuilder
to manually build a third module, the sole purpose of which will be to bind the required class.
Injector injector = Injector.of(
new MessageModule(),
new IdModule(),
ModuleBuilder.create()
.bind(Injected.class)
.build());
Finally, we can request an instance of Injected
from the injector. All fields are correctly injected.
Injected instance = injector.getInstance(Injected.class);