as we can bind a type with its implementation. in case we want to map a type with multiple implmentations, we can create custom annotation as well. see the below example to understand the concept.
create a binding annotation
@bindingannotation @target({ field, parameter, method }) @retention(runtime)
@interface winword {}
-
@bindingannotation - marks annotation as binding annotation.
-
@target - marks applicability of annotation.
-
@retention - marks availablility of annotation as runtime.
mapping using binding annotation
bind(spellchecker.class).annotatedwith(winword.class).to(winwordspellcheckerimpl.class);
inject using binding annotation
@inject
public texteditor(@winword spellchecker spellchecker) {
this.spellchecker = spellchecker;
}
complete example
create a java class named guicetester.
guicetester.java
import java.lang.annotation.target;
import com.google.inject.abstractmodule;
import com.google.inject.bindingannotation;
import com.google.inject.guice;
import com.google.inject.inject;
import com.google.inject.injector;
import java.lang.annotation.retention;
import static java.lang.annotation.retentionpolicy.runtime;
import static java.lang.annotation.elementtype.parameter;
import static java.lang.annotation.elementtype.field;
import static java.lang.annotation.elementtype.method;
@bindingannotation @target({ field, parameter, method }) @retention(runtime)
@interface winword {}
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(@winword spellchecker spellchecker) {
this.spellchecker = spellchecker;
}
public void makespellcheck(){
spellchecker.checkspelling();
}
}
//binding module
class texteditormodule extends abstractmodule {
@override
protected void configure() {
bind(spellchecker.class).annotatedwith(winword.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.