Monday, March 3, 2014

Make life easy with Guice

I decided to write my experience with Guice and how I have used it but before moving fwd Would like to announce it has nothing to do with Guice Tutorial or Guide. It's about my experience with Guice and it's usages as I conceived.

First I would like to announce that Guice has made my life hell lot easier and organised. I may not be the expert but would not mind to achieve the pinnacle :).

Without contradicting I model Guice into 2 parts. Binder and Injector.

"Without Binding no Injection" - was quite clear in first read.

 But I wanted more. How I can use Binding along as I see it as a tool to provide me instance of class. But how to achive it was the question.

But I discovered the answer but may or may not be the best but who wants to be the best ?
"Best is degrading"

I create  ClassInstanceLocator.


public class ClassInstanceLocator {
 private static Injector injector = null;
 
 /**
         * Get Class Instance
         */
 public static <T> T getInstance(final Class<T> t) {
  return injector.getInstance(t);
 }

 /**
  * Initialize Modules during bootstraping.
         * It should be initialized during bootstraping thus making it thread aware.
  * 
  * @param modules
  */
 public synchronized static void initializeModule(final AbstractModule... modules) {

  /* Common module should iniitialized as rest module depends on it
                 * One can make it conditional so that once 
                 *commond is initialized should not be initialized again 
                 */
                if(injector==null){
                 injector = Guice.createInjector(new CommonModule());
                }
  
  if (modules != null) {
   injector = injector.createChildInjector(modules);
  }
 }

 /**
  * Destroys Guice injection tree
  */
 public synchronized static void deInitializeModules() {
  
  injector = null;
 }
 
 /**
  * 
  * @return - Are modules Initialized
  */
 public static boolean isModulesInitialized() {
  return injector != null;
 }

 
}

My life became so easy after this beautiful piece of code. Infact I sometime feel, I am abusing it and become so much addictive of it that I have stop using new. Any way the whole idea of life is to make it more simple.

I can count lot of benefit if I am using it like this.

  • I can always change my implementation from single place without changing it's usages even if it's a concrete class.
  • I can always make class instance as  Singleton as and when I need.
    There are many more I am sure. Without doubt  it's Guice which gives me this liberty, But I am just trying to maximize on it.

Happy Injecting happyness in life.

Adios 
Prabhat