This is just some scribblings on Google Guice, which came together while trying to grasp the workings of the framework.
My reason for understanding the framework, comes from my desire to use DI in android development and in my search for a framework I came across RoboGuice which are a DI framework specifically made for the android platform. RoboGuice builds on Guice and therefore I had to refresh my Guice skills.
Check the RoboGuice website here: http://code.google.com/p/roboguice/
There are two main concepts in Guice, modules and injectors.
Modules are the place where object graphs are defined, this is done by extending the AbstractModule class and overriding the configure() method. AbstractModule contains methods that let's you define how objects are composed, like the example below, were a Service interface is binded to a specific implementation. The injection itself is done using the @Inject annotation like shown below.
Bindings:
public class DependecyModule extends AbstractModule {
@Override
protected void configure() {
bind(SomeService.class).to(SomeServiceImpl.class);
bind(SomeDao.class).to(SomeDaoImpl.class);
}
}Injection:
public class Application {
private SomeService someService;
private SomeDao someDao;
@Inject
public Application(SomeService someService, SomeDao someDao){
this.someService = someService;
this.someDao = someDao;
}
public void work(){
someService.doServiceStuff();
someDao.persistSomething(new Integer("1234"));
}
...
}To get the configured objects you use the Injector class that generates the desired object with all the dependencies injected into the returned object.
Injector use:
public static void main(String[] args) {
Injector injector = Guice.createInjector(new DependecyModule());
Application worker = injector.getInstance(Application.class);
worker.doSomeOrchestration();
}It's that easy, go and get yourself guiced up!!


1 comment:
You have made me understand the concept of RoboGuice with your RoboGuice Tutoirals. Thank you!
Post a Comment