Google Guice Tutorial

admin  

What is Google Guice

Google Guice is a light java dependency inversion framework using annotations. It is developed by Google(Bob Lee and Kevin Bourrillion) and it is used internally by Google for their applications. Google Guice is sometimes considered an Inversion of Control Container but as their authors state it’s not a container, it’s just an Dependency Injector, being too light to be considered a container. Beside Dependency injection Google Guice does some more AOP stuff. However in this tutorial we are going to talk only about the Dependency Injection part. In order to use Google Guice

download it and add the jar from the downloaded zip to the classpath of your application.

First of all let’s take a look on what Google Guice does, then we’ll check how it’s doing it. Let’s take the following sample composed of a few classes:

Customer – contains the customer data – email address, …
Notifier – the interface used to notify a recipient. The customer object contains a reference to the Notifier object.
SendMail – an implementation of the Notify interface which notifies a client about the occurred changes by sending an email.
SendSMS - another implementation of the Notify interface notifying a client by sending an SMS.

Let’s see the code when we don’t use any dependency injection framework:

public class Customer {
      private Notifier notifier;

      public Notifier getNotifier() {
            return notifier;
      }

      public void setNotifier(Notifier notifier) {
            this.notifier = notifier;
      }

      public void changeSomething(){
            this.notifier.sendNotification("This Customer");
      }
}

public interface Notifier {

      public void sendNotification(String to);

}

public class SendMail implements Notifier{

      public void sendNotification(String to){

            System.out.println("Notifying " + to);
      }
}

public class SendSMS implements Notifier{
      public void sendNotification(String to){
            System.out.println("Notifying " + to);
      }
}

public class Main {

      public static void main(String[] args) {

            Customer customer = new Customer();
            Notifier notifier = new SendMail();
            customer.setNotifier(notifier);
            customer.changeSomething();
      }
}

Using Google Guice injector with default bindings defined through annotations.

Now lets use Guice as a dependency injector. First of all we can communicate to Guice the default implementation for the Notifier interface, by using annotations:

@ImplementedBy(SendMail.class)
public interface Notifier {
    public void sendNotification(String to);
}

Then we have to change the “application” code. Instead of using new keyword to create a new object we use the getInstance method of the injector Guice creates for us:

public static void main(String[] args) {
    Injector injector = Guice.createInjector();
    Customer customer = injector.getInstance(Customer.class);
    customer.changeSomething(); // the customer must be notified about the change
}

Then the last step, we must to tell Guice what to inject in the Customer object. We have here 3 options: Field Injection, Method Injection, Constructor Injection:

  1. Field Injector - Guice will create an object of type Notifier (Guice already knows from the first step that the default implementation for Notifier is SendMail) and inject it in the field “Notifier” of the Customer object. Guice is using reflection here and the interesting part here is that it can inject into private and protected fields as well, breaking the encapsulation:
@Inject
private Notifier notifier;
  1. Method Injector:
@Inject
public void setNotifier(Notifier notifier) {
    this.notifier = notifier;
}
  1. Constructor Injector:
public class Customer {
…
      @Inject
      public Customer(Notifier notifier) {
            this.notifier = notifier;
      }
…
}

Defining new bindings

Well done until now, it seems we have everything in place, but what happens if we want to add another notifier class and change the default behavior? Of course we don't want to change the annotations in the interfaces changing the default implementation. What we need is to define new bindings. To do this Guice provide a mechanism which assume the creation of another class called Module, that overwrite the bindings. Let's say we have another Notifier class, SendSMS and we want to use it. We need to create a module class:

public class MyModule implements Module{

    public void configure(Binder binder) {
        binder.bind(Notifier.class).to(SendSMS.class);
    }
}

Now we have the class where we defined the bindings. All we have to do is to tell to the injector to use those bindings. This is how the main method looks:

public static void main(String[] args) {
    MyModule module = new  MyModule();
    Injector anotherInjector = Guice.createInjector(module);

    Customer customer = anotherInjector.getInstance(Customer.class);
    customer.changeSomething();
}

Conclusion

We've seen 3 main Google Guice classes in action in this tutorial. Google Guice mainly consists of those classes along with a few other classes which we haven't seen in action yet:
Binder, Binding - classes responsible for keeping the mapping between interfaces and the implementations that has to be used.
Injector - Fulfills requests for the object instances that make up your application, always ensuring that these instances are properly injected before they are returned.
Module - defines sets of bindings. Modules classes can be used to create injectors (passing a reference to the injector constructor) so the injector uses the binding defined in this.
Provider - provides instances of the applications and can encapsulate some logic to provide one type of implementation or another depending on a context
Scope - helps defining the scope of different injected instances. By scoping Guice offer the option to reuse object instances inside a defined scope (for example reusing objects inside the scope of a session).

In a next part of the tutorial I'll try to check in more depth what Google Guice is capable of.