目录

Guice - 概述

Guice是一个基于Java的开源依赖注入框架。 它非常轻巧,由Google积极开发/管理。

依赖注入

每个基于Java的应用程序都有一些对象可以协同工作,以呈现最终用户所看到的工作应用程序。 在编写复杂的Java应用程序时,应用程序类应尽可能独立于其他Java类,以增加重用这些类的可能性,并在单元测试时独立于其他类测试它们。 依赖注入(或称为布线)有助于将这些类粘合在一起,同时保持它们独立。

假设您有一个具有文本编辑器组件的应用程序,并且您想要提供拼写检查。 您的标准代码看起来像这样 -

public class TextEditor {
   private SpellChecker spellChecker;
   public TextEditor() {
      spellChecker = new SpellChecker();
   }
}

我们在这里做的是,在TextEditor和SpellChecker之间创建依赖关系。 在控制场景的反转中,我们会做这样的事情 -

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

在这里,TextEditor不应该担心SpellChecker的实现。 SpellChecker将独立实现,并在TextEditor实例化时提供给TextEditor。

使用Guice进行依赖注入(绑定)

依赖注入由Guice Bindings控制。 Guice使用绑定​​将对象类型映射到它们的实际实现。 这些绑定定义为一个模块。 模块是绑定的集合,如下所示 -

public class TextEditorModule extends AbstractModule {
   @Override 
   protected void configure() {
      /*
         * Bind SpellChecker binding to WinWordSpellChecker implementation 
         * whenever spellChecker dependency is used.
      */
      bind(SpellChecker.class).to(WinWordSpellChecker.class);
   }
}

Module是Injector的核心构建块,它是Guice的对象图构建器。 第一步是创建一个注入器,然后我们可以使用注入器来获取对象。

public static void main(String[] args) {
   /*
      * Guice.createInjector() takes Modules, and returns a new Injector
      * instance. This method is to be called once during application startup.
   */
   Injector injector = Guice.createInjector(new TextEditorModule());
   /*
      * Build object using injector
   */
   TextEditor textEditor = injector.getInstance(TextEditor.class);   
}

在上面的示例中,TextEditor类对象图由Guice构造,该图包含TextEditor对象及其作为WinWordSpellChecker对象的依赖关系。

↑回到顶部↑
WIKI教程 @2018