Google Guice Tutorial on Google Guice On Demand Injection

injection is a process of injecting dependeny into an object. method and field injections can be used to initialize using exiting object using injector.injectmembers() method. see the example below.

example

create a java class named guicetester.

guicetester.java

import com.google.inject.abstractmodule;
import com.google.inject.guice;
import com.google.inject.implementedby;
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());
      spellchecker spellchecker = new spellcheckerimpl();
      injector.injectmembers(spellchecker);
      
      texteditor editor = injector.getinstance(texteditor.class);     
      editor.makespellcheck();
   } 
}

class texteditor {
   private spellchecker spellchecker;

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

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

//binding module
class texteditormodule extends abstractmodule {

   @override
   protected void configure() {      
   } 
}

@implementedby(spellcheckerimpl.class)
interface spellchecker {
   public void checkspelling();
}

//spell checker implementation
class spellcheckerimpl implements spellchecker {

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

output

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

inside checkspelling.