Google Guice Tutorial on Google Guice First Application

let's create a sample console based application where we'll demonstrate dependency injection using guice binding mechanism step by step.

step 1: create interface

//spell checker interface
interface spellchecker {
   public void checkspelling();
}

step 2: create implementation

//spell checker implementation
class spellcheckerimpl implements spellchecker {
   @override
   public void checkspelling() {
      system.out.println("inside checkspelling." );
   } 
}

step 3: create bindings module

//binding module
class texteditormodule extends abstractmodule {
   @override
   protected void configure() {
      bind(spellchecker.class).to(spellcheckerimpl.class);
   } 
}

step 4: create class with dependency

class texteditor {
   private spellchecker spellchecker;
   @inject
   public texteditor(spellchecker spellchecker) {
      this.spellchecker = spellchecker;
   }
   public void makespellcheck(){
      spellchecker.checkspelling();
   }
}

step 5: create injector

injector injector = guice.createinjector(new texteditormodule());

step 6: get object with dependency fulfilled.

texteditor editor = injector.getinstance(texteditor.class);

step 7: use the object.

editor.makespellcheck(); 

complete example

create a java class named guicetester.

guicetester.java

import com.google.inject.abstractmodule;
import com.google.inject.guice;
import com.google.inject.inject;
import com.google.inject.injector;

public class guicetester {
   public static void main(string[] args) {
      injector injector = guice.createinjector(new texteditormodule());
      texteditor editor = injector.getinstance(texteditor.class);
      editor.makespellcheck(); 
   } 
}

class texteditor {
   private spellchecker spellchecker;

   @inject
   public texteditor(spellchecker spellchecker) {
      this.spellchecker = spellchecker;
   }

   public void makespellcheck(){
      spellchecker.checkspelling();
   }
}

//binding module
class texteditormodule extends abstractmodule {

   @override
   protected void configure() {
      bind(spellchecker.class).to(spellcheckerimpl.class);
   } 
}

//spell checker interface
interface spellchecker {
   public void checkspelling();
}


//spell checker implementation
class spellcheckerimpl implements spellchecker {

   @override
   public void checkspelling() {
      system.out.println("inside checkspelling." );
   } 
}

output

compile and run the file, you will see the following output.

inside checkspelling.