Google Guice – Named Bindings

Google Guice - Named Bindings

This topic is about Google Guice – Named Bindings.

Guice provides another way also to map bindings without creating a custom annoation. It allows so using @Named annotation.

Mapping using named annotation

bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice")).to(OpenOfficeWordSpellCheckerImpl.class);

Inject using @Named annotation

@Inject
public TextEditor(@Named("OpenOffice") SpellChecker spellChecker) {
   this.spellChecker = spellChecker;
}

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;
import com.google.inject.name.Named;
import com.google.inject.name.Names;

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(@Named("OpenOffice") SpellChecker spellChecker) {
      this.spellChecker = spellChecker;      
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling(); 
   }  
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
      bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice"))
         .to(OpenOfficeWordSpellCheckerImpl.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." );
   } 
}

//subclass of SpellCheckerImpl
class OpenOfficeWordSpellCheckerImpl extends SpellCheckerImpl{
   @Override
   public void checkSpelling() {
      System.out.println("Inside OpenOfficeWordSpellCheckerImpl.checkSpelling." );
   } 
}

Output

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

Inside OpenOfficeWordSpellCheckerImpl.checkSpelling.

In this topic we learned about Google Guice – Named Bindings. To know more, Click Here.

This Post Has 2 Comments

  1. One more thing I would like to convey is that in place of trying to accommodate all your online degree training on times that you complete work (since the majority people are exhausted when they get back), try to find most of your classes on the week-ends and only a couple courses for weekdays, even if it means taking some time off your weekend break. This is really good because on the saturdays and sundays, you will be a lot more rested plus concentrated with school work. Thanks alot : ) for the different suggestions I have discovered from your web site.

Leave a Reply