Saturday, November 28, 2009

Guice-ing your code

During my learning on shindig, i found out that shindig using guice a lot on its code. Of course, I try to find out what is this tool about. After a little bit searching, I found out that the it is a bit similar with Spring. However, the authors say that it is different. They say that guice is not container and it is too light to be container. Anyway, just cut the bullshit and try to find out what is this tool about.

The first impression on my side after trying this tool is simple. Well, yes... it is indeed very simple as a dependency injection framework. What you need to do is the annotation. It makes all the things very simple.

The things that you need to remember (well, at least on my simple try) on regard of guice-ing your codes is the injector. The injector will try to lookup what are the fields, methods or constructor which need to be injected with object. Then, guice will inject it for you.

Below is a little bit example on it:

public static void main(String[] args) {
// TODO Auto-generated method stub
Injector injector = Guice.createInjector();
Customer customer = injector.getInstance(Customer.class);
customer.changeItem("barangnya");
}

The method injector.getInstance(Customer.class) will give you a complete object of customer with the injected notifier object. Below is the class of Customer:

public class Customer {
@Inject
public Notifier notifier;
public void changeItem(String message)
{
notifier.sendNotification(message);
}
}


Notifier is an interface. Guice will lookup on this interface to find out what class implement Notifier interface. In order to know what class which implemet Notifier interface, the interface should define annotation to tell the guice. Below is the interface of Notifier.

@ImplementedBy(SendSms.class)
public interface Notifier {
public void sendNotification(String message);
}


Its easy, isnt it (well, at least for this try :P)?

No comments: