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();
}
}
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;
}
…
}
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();
}
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.
6 Responses
Jonhnny Weslley
25|Apr|2008 1Great 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;
}
…
}
admin
25|Apr|2008 2You’re right, I’ve updated the article. Thanks for the remark
WurstFromHell
25|Apr|2008 3Nice 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!
admin
26|Apr|2008 4Fixed it in the post.
Thanks:)
Gregg Bolinger
29|Apr|2008 5Good 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?
admin
29|Apr|2008 6As 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…
Leave a reply
Search
Categories
Blogroll
Recent Posts
Recent Comments
Tags
.NET Annotations Ant bazaar Build bzr Castor compile configuration CSharp data binding Dependency Injection Dependency Inversion Design Patterns Eclipse funny generics google Google Collections guice Hibernate How To Ant Inheritance Injector jar Java Java Frameworks java properties java snippets Jaxb Marker Interface marshalling packaging persistence plugin Serializable source control Tutorial VB.NET Visitor Pattern warnings XML xmloutput xml serialization XPathA design creation of Design Disease
Copyright © 2007 - FactoryPattern.com - is proudly powered by WordPress
InSense 1.0 Theme by Design Disease