in linked bindings, guice maps a type to its implementation. in below example, we've mapped spellchecker interface with its implementation spellcheckerimpl.
bind(spellchecker.class).to(spellcheckerimpl.class);
we can also mapped the concrete class to its subclass. see the example below:
bind(spellcheckerimpl.class).to(winwordspellcheckerimpl.class);
here we've chained the bindings. let's see the result in complete example.
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);
bind(spellcheckerimpl.class).to(winwordspellcheckerimpl.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 winwordspellcheckerimpl extends spellcheckerimpl{
@override
public void checkspelling() {
system.out.println("inside winwordspellcheckerimpl.checkspelling." );
}
}
output
compile and run the file, you will see the following output.
inside winwordspellcheckerimpl.checkspelling.