My First Google Guice Application
Google Guice is a simple yet interesting Dependency Injector for I just wrote my first Guice application in netbeans. It is a very basic application but was good enough to do a head start. First you need to download Guice from gooogle code site from http://code.google.com/p/google-guice/ . In the zip you will find two jars called guice-2.0.jar and aopalliance.jar which you need to create your application.
First you need to create a normal java application project and then add the above two jar’s in the project as library.
I started with a simple interface like this
package firstguice.interfaces;
public interface IGreeter {
public void sayHello();
}
Next I created the implementation of this as the following code
package firstguice.impl;
import firstguice.interfaces.IGreeter;
public class ConsoleGreeter implements IGreeter{
public void sayHello() {
System.out.println("Hi there, this is the console greeter");
}
}
After the implementation is done. Lets create the module. Where we will be gluing the interface with the implementation.
package firstguice.module;
import com.google.inject.AbstractModule;
import firstguice.impl.ConsoleGreeter;
import firstguice.interfaces.IGreeter;
public class GreeterModule extends AbstractModule {
@Override
protected void configure() {
this.bind(IGreeter.class).to(ConsoleGreeter.class);
}
}
Now time for the actual code in the main function
package firstguice;
import com.google.inject.Guice;
import com.google.inject.Injector;
import firstguice.interfaces.IGreeter;
import firstguice.module.GreeterModule;
public class FirstGuice {
public static void main(String[] args) {
Injector jk=Guice.createInjector(new GreeterModule());
IGreeter greeter=jk.getInstance(IGreeter.class);
greeter.sayHello();
}
}
Comments
I am really glad that you liked my blog :). I have written this blog using Microsoft live writer. Live Writer had this feature of being able to post codes in nice format. But I could not find something equivalent in the blogspots own editor. I found a blog post couple of months back that showed how can we achieve it by using JavaScript code highlighter. But I did not really liked the process. It is just too much for me. You can say I am also looking for something to help me out format the codes better. I will definitely let you know once I got one that really works and easy.