开发手册 欢迎您!
软件开发者资料库

Google Guice - 概述

Google Guice概述 - 从简单和简单的步骤学习Google Guice,从基本到高级概念,包括概述,环境设置,第一个应用程序,绑定示例,链接,@命名,常量,构造函数,内置,即时绑定,绑定,@ provides注释,提供者类,注入示例,构造函数,方法,字段,可选,按需,静态,自动注入,范围,AOP。

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);   } }

模块是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对象的依赖.