Google Guice Tutorial

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;

2. Method Injector:

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

3. 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.

Did you enjoy this tutorial? Be sure to subscribe to the my RSS feed not to miss my new posts!
... or make it popular on

18 Comments

  1. Great post!!!

    But the constructor injector is wrong. It’s must to be:
    public class Customer {

    private Notifier notifier;

    @Inject
    public Customer(Notifier notifier) {
    this.notifier = notifier;
    }

    }

  2. Nice article. As I tried your examples I stumbled upon a little mistake at the end:

    Customer customer = injector.getInstance(Customer.class);
    must be
    Customer customer = anotherInjector.getInstance(Customer.class);

    I’m looking forward to your next article!

  3. Good article. The only thing missing is how you bind both Notifier implementations and use one or the other without writing a Module to do the binding. There would be times when you would need to switch between sending and email and sending an SMS in a live environment. How do you handle that?

  4. As I know that’s the only way to change the default binding: creating a Module class. Additionally a Provider (not discussed in this post) class can be created encapsulating some logic to decide at runtime which implementation should be provided.

    The problem you described seems to be solved using a strategy pattern. Maybe I would go for it is I couldn’t create a Module class…

  5. i want to create a new guice factory i do not now method and process so please help me soon

  6. O, but I still don’t get it. I’ve followed this example, implemented and executed it. OK, it’s fine that we can put things differently, but don’t really get the advantage. Actually, it’s kind of weird for debugging, isn’t it?

    And it’s code-invasive. So I’m trying to find an example where I could really see the difference. I guess when we’re using an interface, it’s because in few cases we’ll use an implementation and in another case we’ll use another one, but how shold this be working? I mean, what advanatage I have?

    Apart from that, I have to say you put the easiest post to follow this. Congratulations and thank you.

  7. Nice. This is really useful tutorial for understanding the basics of google guice dependency injection. Thanks a lot.

  8. Most useful post on Guice for the beginner, so far! Very easy to follow, conveying the core concept of Guice. Thanks!!! Is the “next part of the tutorial” up?

  9. Very useful post on Guice for a beginner. Very easy to follow, explaining the basic concepts of Guice. Thank you !! Is the next part of the tutorial available?

Leave a Comment.