Google Guice - 链接绑定
在链接绑定中,Guice 将类型映射到其实现。 在下面的示例中,我们映射了 SpellChecker 接口及其实现 SpellCheckerImpl。
bind(SpellChecker.class).to(SpellCheckerImpl.class);
我们还可以将具体类映射到它的子类。 请参阅下面的示例:
bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class);
这里我们已经链接了绑定。 让我们看看完整示例的结果。
完整示例
创建一个名为 GuiceTester 的 java 类。
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." );
}
}
输出
编译并运行该文件,您将看到以下输出。
Inside WinWordSpellCheckerImpl.checkSpelling.

