Dependency Injection

Dependency Injection & Guice

Description

Dependency injection or "Inversion of Control" are two design patterns whereby a service can be told what dependencies it will work with.

The following example does not use IoC:


class LookupService {
private PhonebookImpl p = new PhonebookImpl();
public String getPhoneNumber() {
return p.getPhoneNumber();
}
}

In the above example, it is impossible to switch out the phonebook object for a different phonebook implementation. So, if PhonebookImpl was using a database backend and we wanted to switch to a Lucene backend, this would be hard. It is also hard to test, as to test the ''getPhoneNumber'' method, I will have to ensure that the creation of PhonebookImpl is possible (i.e. that it can create all its dependants, has a database, etc.). It is hard to mock out that object.

The example below decouples the implementation and creates an interface. It also allows an external service to inject the Phonebook service (whether that be a mock service or a real implementation)


class LookupService {
private final Phonebook p;
public LookupService(Phonebook p) {
this.p = p;
}
public String getPhoneNumber() {
return p.getPhoneNumber();
}
}

In the above example, the object that instantiates LookupService is responsible for providing (injecting) the correct implementation using the constructor provided (constructor injection). You can also achieve the same thing using setters however the caller will then need to be careful to call all the relevant setters and private fields cannot be set to final.

Guice

  • Guice is a framework developed by Google to ease dependency injection
  • Dependency injection is done mostly through constructor injection using the @Inject annotation
  • A "Guice module" bind interfaces to classes (in Singletons or not), in our case ''StepCoreModule''
  • The ''StepCoreModule'' is also reads a property file (step.core.properties). These are available through the @Named annotation, e.g. @Named("app.db.driver")
  • Singletons can be created simply by adding an annotation to the object in question. (@Singleton)
  • Reference data is currently hard coded in the form of Providers (see ''com.tyndalehouse.step.core.guice.providers.DefaultVersionsProvider'' for an example)
  • The example above has been reworked to show the Guice injection. The only difference below is the constructor which is now annotated with @Inject.

class LookupService {
private final Phonebook p;
@Inject
public LookupService(Phonebook p) {
this.p = p;
}
public String getPhoneNumber() {
return p.getPhoneNumber();
}
}

In addition to this, the developer needs to tell the StepCoreModule that Phonebook should use the PhoneBookImpl implementation:

public void configure() {
bind(Phonebook.class).to(PhonebookImpl.class);
}