目录

Guice - 第一次申请( First Application)

让我们创建一个基于控制台的示例应用程序,我们将逐步使用Guice绑定机制演示依赖注入。

第1步:创建界面

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}

第2步:创建实施

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}

第3步:创建绑定模块

//Binding Module
class TextEditorModule extends AbstractModule {
   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
   } 
}

第4步:创建具有依赖性的类

class TextEditor {
   private SpellChecker spellChecker;
   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
   public void makeSpellCheck() {
      spellChecker.checkSpelling();
   }
}

第5步:创建注射器

Injector injector = Guice.createInjector(new TextEditorModule());

步骤6:获取具有依赖性的对象

TextEditor editor = injector.getInstance(TextEditor.class);

第7步:使用该对象

editor.makeSpellCheck(); 

完整的示例 (Complete Example)

创建一个名为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);
   } 
}
//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}

输出 (Output)

编译并运行该文件,您将看到以下输出。

Inside checkSpelling.
↑回到顶部↑
WIKI教程 @2018