Skip to main content

Injecting instances

In this tutorial we will inject instances into classes. We will use 2 approaches:

  • Using an InstanceInjector
  • Adding class that will have its fields injected to the bindings graph

Modules#

We will define two independent modules: one will provide String message, the other one will provide 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 that needs to have its fields injected.

public class Injected {
@Inject
String value;
@Inject
int id;
}

We need to create an Injector and pass both MessageModule and IdModule as parameters.

We also need to add a binding for an instance injector. For that we will use a ModuleBuilder to manually build the third module whose sole purpose will be binding an instance injector.

Injector injector = Injector.of(
new MessageModule(),
new IdModule(),
ModuleBuilder.create()
.bindInstanceInjector(Injected.class)
.build());

Finally, we need to obtain InstanceInjector from the Injector and use it to inject fields into newly created Injected instance.

InstanceInjector<Injected> instanceInjector = injector.getInstanceInjector(Injected.class);
Injected injected = new Injected();
instanceInjector.injectInto(injected);

Adding class to bindings graph#

Here is once againg the class that needs to have its fields injected. Notice, that there is an @Inject annotation this time annotating the type.

@Inject
public class Injected {
@Inject
String value;
@Inject
int id;
}

Alternatively, you may add a constructor and annotate it with @Inject annotation like this:

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 both MessageModule and IdModule as parameters.

However, instead of binding instance injector, this time we will bind Injected class. For that we will also use a ModuleBuilder to manually build the third module whose sole purpose will be binding a reuired class.

Injector injector = Injector.of(
new MessageModule(),
new IdModule(),
ModuleBuilder.create()
.bind(Injected.class)
.build());

Finally, we may request an instance of Injected from the injector. All of the fields are properly injected.

Injected instance = injector.getInstance(Injected.class);