Google Guice结合模式
要创建绑定(Binding)对象,能够继承自AbstractModule类,然后覆盖其configure方法,在方法调用bind()方法来指来定每一次绑定。这些方法带有类型检查,假设你使用了错误的类型编译器就会报告编译错误。假设你已经写好了Module类,则创建一个Module类对象作为參数传递给Guice.createInjector()方法用于创建一个注入器。
通过Module对象能够创建链接绑定(linked bindings)、实例绑定(instance bindings)、@Provides methods、提供者绑定(provider bindings)、构建方法绑定(constructor bindings)与无目标绑定(untargetted bindings)。
这些绑定方式统称为内置绑定,相相应的还有种及时绑定。假设在解析一个依赖时假设在内置绑定中无法找到。那么Guice将会创建一个及时绑定。
一、链接绑定(LinkdedBindings)
链接绑定即映射一类型到它的实现类,比如映射TransactionLog接口到实现类DatabaseTransactionLog:
public class BillingModule extends AbstractModule {@Override protected void configure() {bind(TransactionLog.class).to(DatabaseTransactionLog.class);}
}
这样,当你调用injector.getInstance(TransactionLog.class)方法,或者当注入器碰到TransactionLog依赖时,就会使用DatabaseTransactionLog对象。链接是从一类型到它不论什么的子类型,这包含接口实现类,类的子类;所以例如以下映射也是能够的:bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
而且链接绑定支持链式写法:
public class BillingModule extends AbstractModule {@Override protected void configure() {bind(TransactionLog.class).to(DatabaseTransactionLog.class);bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);}
}
在这样的情况下,当请求一个TransactionLog类型对象时,注入器将返回一个MySqlDatabaseTransactionLog对象。
二、绑定注解
某些情况下你可能想为同一种类型设置多种绑定。这就能够通过绑定注解来实现,该注解与绑定的类型用于唯一结识一个绑定,
合在一起称为Key。演示样例:
package example.pizza;import com.google.inject.BindingAnnotation;
import java.lang.annotation.Target;
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)
public @interface PayPal {}
这里关键的是@BindingAnnotation元注解,当Guice描写叙述到该注解时,就会把PayPal作为绑定注解。
然后在Module的configure方法中使用annotatedWith语句,例如以下:
bind(CreditCardProcessor.class).annotatedWith(PayPal.class).to(PayPalCreditCardProcessor.class);
这样就把CreditCardProcessor映射到了PayPalCreditCardProcessor。
使用方法:
public class RealBillingService implements BillingService {@Injectpublic RealBillingService(@PayPal CreditCardProcessor processor,TransactionLog transactionLog) {...}
}
另一种情况,我们能够使用Guice已经定义好的@Named注解。比如:
public class RealBillingService implements BillingService {@Injectpublic RealBillingService(@Named("Checkout") CreditCardProcessor processor,TransactionLog transactionLog) {...}
}
要绑定一详细名称,使用Names.named()来创建一个实现传给annotatedWith方法:
bind(CreditCardProcessor.class).annotatedWith(Names.named("Checkout")).to(CheckoutCreditCardProcessor.class);
由于编译器不会对字符串进行检查,Guice建议我们少使用@Named注解,可是我个人觉得,仅仅要自己写代码时仅仅要名称不要写错,
通过这样的方法式是最easy为同一类型映射多个绑定的。这非常类似Spring中的实现方式,Spring的@Service,@Controller,@Repository不就能够指定名称吗?
三、实例绑定(Instance Bindings)
通过实例绑定我们能够为某类型绑定一个详细的实例,这只适用于这些实例类型没有其他依赖的情况,比如值对象:
bind(String.class).annotatedWith(Names.named("JDBC URL")).toInstance("jdbc:mysql://localhost/pizza");bind(Integer.class).annotatedWith(Names.named("login timeout seconds")).toInstance(10);
使用方式:
@Inject @Named("JDBC URL")
private String url
Guice建议我们避免使用.toInstance来创建复杂的对象。由于这会延迟应用启动。类似地,能够使用@Provides方法实现。
四、@Provides方法
当使用@Provides方法创建对象时。该方法必须定义在Module类中。而且它必须加以@Provides注解。该方法的返回值类型就是被绑定的对象。
当注入器须要该类型的实例时,它就会来调用该方法。
public class BillingModule extends AbstractModule {@Overrideprotected void configure() {...}@ProvidesTransactionLog provideTransactionLog() {DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");transactionLog.setThreadPoolSize(30);return transactionLog;}
}
假设在@Provides方法上有@PayPal或@Named("Checkout")绑定注解。Guice以绑定注解优先。Guice在调用@Provides方法之前会先解析该方法的依赖:
@Provides @PayPal
CreditCardProcessor providePayPalCreditCardProcessor(@Named("PayPal API key") String apiKey) {PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();processor.setApiKey(apiKey);return processor;
}
关于异常:
Guice不同意在@Provides方法中抛出异常。
假设有异常抛出。那么异常将会被包装在ProvisionException对象中。
五、提供者绑定(Provider Bindings)
假设@Provides方法越来越复杂。我们可能会想把它们移到一个单独的类中。一个提供者类实现了Provider接口。它是一个
用于提供值的简单通用接口。
public interface Provider<T> {T get();
}
假设提供者实现类有其自己的依赖时,能够通过在其构造方法上加入@Inject注解进行注入,以保证值安全返回。
public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {private final Connection connection;@Injectpublic DatabaseTransactionLogProvider(Connection connection) {this.connection = connection;}public TransactionLog get() {DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();transactionLog.setConnection(connection);return transactionLog;}
}
最后使用.toProvider语句来绑定到提供者:
public class BillingModule extends AbstractModule {@Overrideprotected void configure() {bind(TransactionLog.class).toProvider(DatabaseTransactionLogProvider.class);}
}
六、无目标绑定
Guice同意我们创建绑定时不指定目标类。也就是没有to语句,这对于详细类或者使用了@ImplementedBy或@ProvidedBy注解类型非常实用。比如:
bind(MyConcreteClass.class);
bind(AnotherConcreteClass.class).in(Singleton.class);
然而,在使用绑定注解时,我们依赖必须指定绑定目标。即它是一个详细类,比如:
bind(MyConcreteClass.class).annotatedWith(Names.named("foo")).to(MyConcreteClass.class);
bind(AnotherConcreteClass.class).annotatedWith(Names.named("foo")).to(AnotherConcreteClass.class).in(Singleton.class);
七、构造方法绑定
有些时候你可能须要将某一类型绑定到任一构建方法,比如在@Inject注解无法加入到目标类构造方法,其原因可能是这个类是
第三方提供的。或者说该类有多个构建方法參与依赖注入。此时@Provides方法是解决问题的最好方案,由于它能够明白指定
调用哪个构造方法。并且不须要使用反射机制。
可是使用@Provides方法在某些地方有限制,比如:手动创建对象不能在AOP中使用。
正是由于这个原因,Guice使用了toConstructor()进行绑定。这须要我们使用反射来选择构造方法与处理异常。
public class BillingModule extends AbstractModule {@Override protected void configure() {try {bind(TransactionLog.class).toConstructor(DatabaseTransactionLog.class.getConstructor(DatabaseConnection.class));} catch (NoSuchMethodException e) {addError(e);}}
}
上这个样例中DatabaseTransactionLog类必须有一个带DatabaseConnection參数的构造方法,该构造方法中不须要使用@Inject注解Guice会自己主动调用该构造方法。每一条toConstructor()语句创建的绑定。其作用域是独立的,假设你创建了多个单例绑定而且使用目标类的同一个构造方法,每个绑定还是拥有各自的实例。
八、及时绑定
当注入器须要某一类型实例的时候。它须要获取一个绑定。在Module类中的绑定叫做显示绑定,仅仅要它们可用,注入器就能够使用它们。假设须要某一类型实例,但它又不是显示绑定。那么注入器将试图创建一个及时绑定(Just-In-Time bindings),它也被称为JIT绑定与隐式绑定。
可用于创建及时绑定的情况例如以下:
a.有一个合适的构建方法,即非私有。不带參数或者标有@Inject注解的构造方法,比如:
public class PayPalCreditCardProcessor implements CreditCardProcessor {private final String apiKey;@Injectpublic PayPalCreditCardProcessor(@Named("PayPal API key") String apiKey) {this.apiKey = apiKey;}
}
Guice不会创建内部类实例除非它有static修饰符,由于内部类含有一个指向外问类的隐式引用,而这个隐式引用无法注入。
b. @ImplementedBy
@ImplementedBy注解于用告诉注入器某类型的缺省实现类型是什么,这与链接绑定非常相似。
为某一类型绑定一子类型例如以下:
@ImplementedBy(PayPalCreditCardProcessor.class)
public interface CreditCardProcessor {ChargeResult charge(String amount, CreditCard creditCard)throws UnreachableException;
}
@ImplementedBy(PayPalCreditCardProcessor.class)等效于以下的bind()语句:
bind(CreditCardProcessor.class).to(PayPalCreditCardProcessor.class);
假设某一类型即有bind()语句又有@ImplementedBy注解。则bind()语句优先。使用@ImplementedBy请小心,由于它为接口加入了编译时依赖。
c. @ProvidedBy
@ProvidedBy注解用于告诉注入器。Provider类的实现是什么,比如:
@ProvidedBy(DatabaseTransactionLogProvider.class)
public interface TransactionLog {void logConnectException(UnreachableException e);void logChargeResult(ChargeResult result);
}
这等价于bind(TransactionLog.class).toProvider(DatabaseTransactionLogProvider.class);
类似@ImplementedBy注解,假设某个类型既使用了bind()语句,又使用了@ProvidedBy注解。然后,bind()声明优先。
版权声明:本文博主原创文章,博客,未经同意不得转载。
转载于:https://www.cnblogs.com/mengfanrong/p/4829214.html
Google Guice结合模式相关推荐
- guice 框架_玩! 框架+ Google Guice
guice 框架 在我目前正在工作的项目中,我们开始使用Google Guice. 对于那些不知道的人, Google Guice是一个依赖项注入框架. 依赖项注入的基本思想是提供一个其依赖的类,而不 ...
- 玩! 框架+ Google Guice
在我目前正在工作的项目中,我们开始使用Google Guice. 对于那些不知道的人, Google Guice是一个依赖项注入框架. 依赖项注入背后的基本思想是提供一个它依赖的类,而不是使依赖类负责 ...
- guice google_与Google Guice的动手实践
guice google by Sankalp Bhatia 通过Sankalp Bhatia 与Google Guice的动手实践 (A hands-on session with Google G ...
- Google Guice使用入门
2019独角兽企业重金招聘Python工程师标准>>> 本文通过范例简单地介绍Google Guice的使用,通过下面的范例我们可以知道,Google Guice的使用非常简单. G ...
- Google Guice范例解说之使用入门
http://www.cnblogs.com/xd502djj/archive/2012/06/25/2561414.html Google Guice范例解说之使用入门 http://code.go ...
- 超轻量级DI容器框架Google Guice与Spring框架的区别教程详解及其demo代码片段分享...
超轻量级DI容器框架Google Guice与Spring框架的区别教程详解及其demo代码片段分享 DI框架 Google-Guice入门介绍 转载于:https://www.cnblogs.com ...
- guice 实例_使用Google Guice消除实例之间的歧义
guice 实例 如果接口有多个实现,则Google guice提供了一种精巧的方法来选择目标实现. 我的示例基于Josh Long ( @starbuxman )的出色文章,内容涉及Spring提供 ...
- 使用Google Guice消除实例之间的歧义
如果接口有多个实现,则Google guice提供了一种精巧的方法来选择目标实现. 我的示例基于Josh Long ( @starbuxman )的出色文章,内容涉及Spring提供的类似机制. 因此 ...
- Google Guice 一个轻量级的依赖注入框架
1.美图 2.概述 2.1 背景 在做项目的时候,看见有段代码直接是使用Google Guice 注入了avaitor表达式. 2.1 官网 Github 主页:https://github.com/ ...
最新文章
- Typedef用法学习
- Unity2D游戏开发基础教程1.2项目、资源和场景
- Linux命令(一)
- HTTP面试题都在这里
- DynamicArray
- Mssql 跨域查询
- 高端中餐美食餐饮海报PSD模板,看着就有食欲
- 图解TCPIP-NAT
- Java声明字符串数组,架构师必备!
- 20145202 《信息安全系统设计基础》第6周学习总结(2)
- java模拟器下载文件_KEmulator(java模拟器)最新下载
- AndroidOTA增量包(差分包)制作记录
- 【侯捷】C++ STL
- 【资源下载】《Oracle DBA手记》第1篇:DBA工作手记
- 三菱编程软件GX Works2
- python两点画线_在图像python matplotlib的两点之间画一条线
- 学习ARM开发(6)
- 传统教培机构搭建网校平台是否成必然的趋势?
- c语言菜单 键盘,三、Windows键盘快捷键—处理菜单项
- 个人常用命令集锦 持续更新
热门文章
- Web前端开发面试题---HTML+CSS
- 排序的几种方法 oc
- 为CodeLove编写插件——常用软件扫描(SoftwareToScan)
- spring实例化bean的方式
- 几种适合开发用的在线编辑器-推荐及下载
- UML 中各种图形重要性的排行
- 第十一篇 SpringBoot 2 x整合Swagger2
- Chrome Console Cookie 控制台操作命令
- Cisco IPSec *** Gre over --- SVTI
- $(document).ready、body.Onload()和 $(window).load的区别