Google Guice学习
学习动力:公司项目使用
官方文档:https://github.com/google/guice/wiki/Motivation
学习阶段:入门
主要部份:
简介
Guice通过注解方式提供以来注入,一种方式是通过@Injuct注入构造函数
class BillingService {
private final CreditCardProcessor processor;
private final TransactionLog transactionLog;
@Inject
BillingService(CreditCardProcessor processor,
TransactionLog transactionLog) {
this.processor = processor;
this.transactionLog = transactionLog;
}
public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {
...
}
}
然后通过Module来绑定接口与实现类
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
/*
* This tells Guice that whenever it sees a dependency on a TransactionLog,
* it should satisfy the dependency using a DatabaseTransactionLog.
*/
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
/*
* Similarly, this binding tells Guice that when CreditCardProcessor is used in
* a dependency, that should be satisfied with a PaypalCreditCardProcessor.
*/
bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
}
}
最后通过Injector.getInstance(),通过接口类和Module获得实现类,减少了和具体类之间的耦合,让代码结构更加稳定,易于测试。
public static void main(String[] args) {
/*
* Guice.createInjector() takes your Modules, and returns a new Injector
* instance. Most applications will call this method exactly once, in their
* main() method.
*/
Injector injector = Guice.createInjector(new BillingModule());
/*
* Now that we've got the injector, we can build objects.
*/
BillingService billingService = injector.getInstance(BillingService.class);
...
}
Bindings方式
1.Linked Bindings方式
Linked Bindings将一个类型与它的实现类绑定。甚至可以将一个具体类型与它的子类绑定。绑定关系可以串联。
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
}
}
2.Binding Annotations方式
有时候我们需要将多个实现类绑定到同一个类型上面。比如在BillingService中,我们需要将PayPal credit card processor和Google Checkout processor 绑定到同一个CreditCardProcessor类型上。 Binding Annotations提供几种方式来实现,项目中使用比较多的是这种@Named。我们在需要注入的地方这样写:
public class RealBillingService implements BillingService {
@Inject
public RealBillingService(@Named("Checkout") CreditCardProcessor processor,
TransactionLog transactionLog) {
...
}
然后在Module中这样绑定:
bind(CreditCardProcessor.class)
.annotatedWith(Names.named("Checkout"))
.to(CheckoutCreditCardProcessor.class);
3.Instance Bindings
对于无法继承的类(比如String和Integer),可以使用toInstance()来绑定。
bind(String.class)
.annotatedWith(Names.named("JDBC URL"))
.toInstance("jdbc:mysql://localhost/pizza");
bind(Integer.class)
.annotatedWith(Names.named("login timeout seconds"))
.toInstance(10);
4.@Provides Methods
使用@Provides可以通过创建一个方法来提供所需类型的实现,当需要这个类型的时候,injector就会调用这个方法。
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
...
}
@Provides
TransactionLog provideTransactionLog() {
DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");
transactionLog.setThreadPoolSize(30);
return transactionLog;
}
}
5.Provider Bindings
当@Provides 方法越来越复杂的时候,你会考虑使用一个Provider类来管理。Guice提供了Provider这个接口。Provider自身可能也有需要注入的组件。
下面是一个例子
public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {
private final Connection connection;
@Inject
public DatabaseTransactionLogProvider(Connection connection) {
this.connection = connection;
}
public TransactionLog get() {
DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
transactionLog.setConnection(connection);
return transactionLog;
}
}
然后我们使用toProvider()将Provider和需要注入的类型绑定。
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class)
.toProvider(DatabaseTransactionLogProvider.class);
}
6.Untargeted Bindings
当需要绑定具体类,或是使用@ImplementedBy和@ProvidedBy的类型时,可以直接bind(),不加上to()
bind(MyConcreteClass.class);
bind(AnotherConcreteClass.class).in(Singleton.class);
7.Constructor Bindings
当需要注入的对象来自第三方库,或是有多个构造函数的时候,我们不能使用@Injuct,这时可以使用@Provides可以解决问题!
但是因为一个什么原因(我没看懂),这也提供了一种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);
}
}
}
Scopes设定
依赖注入框架既然帮忙注入对象,自然也要管理对象的生命周期Scope。Guice中通过注解来设定对象的Scope。
Guice中典型的生命周期有for the lifetime of an application (@Singleton), a session (@SessionScoped), or a request (@RequestScoped)
可以在相应的实现类上标注。
@Singleton
public class InMemoryTransactionLog implements TransactionLog {
/* everything here should be threadsafe! */
}
或是通过跟在bind()后的in()来设定。
bind(TransactionLog.class).to(InMemoryTransactionLog.class).in(Singleton.class);
或是在@Provides方法上标注。
@Provides @Singleton
TransactionLog provideTransactionLog() {
...
}
当类型上的Scope和bind()方法后in()的Scope冲突时,bind()的Scope会被使用。
还有一些比较复杂的概念,延迟加载,需要深入理解的时候在再看吧。
Injecting Providers
我理解这一章的内容是使用Provider来替代接口作为注入的入口的好处。
当你需要多次获得一个新的注入对象时,使用Provider
public class LogFileTransactionLog implements TransactionLog {
private final Provider<LogFileEntry> logFileProvider;
@Inject
public LogFileTransactionLog(Provider<LogFileEntry> logFileProvider) {
this.logFileProvider = logFileProvider;
}
public void logChargeResult(ChargeResult result) {
LogFileEntry summaryEntry = logFileProvider.get();
summaryEntry.setText("Charge " + (result.wasSuccessful() ? "success" : "failure"));
summaryEntry.save();
if (!result.wasSuccessful()) {
LogFileEntry detailEntry = logFileProvider.get();
detailEntry.setText("Failure result: " + result);
detailEntry.save();
}
}
当你需要延迟加载一些重要对象,特别是它并不总是需要加载时,使用Provider
public class DatabaseTransactionLog implements TransactionLog {
private final Provider<Connection> connectionProvider;
@Inject
public DatabaseTransactionLog(Provider<Connection> connectionProvider) {
this.connectionProvider = connectionProvider;
}
public void logChargeResult(ChargeResult result) {
/* only write failed charges to the database */
if (!result.wasSuccessful()) {
Connection connection = connectionProvider.get();
}
}
如果你不希望对象的生命周期混杂,比如一个Singleton的Logger和一个RequestScope的User在一起使用就可能会出现问题。
@Singleton
public class ConsoleTransactionLog implements TransactionLog { private final AtomicInteger failureCount = new AtomicInteger();
private final Provider<User> userProvider; @Inject
public ConsoleTransactionLog(Provider<User> userProvider) {
this.userProvider = userProvider;
} public void logConnectException(UnreachableException e) {
failureCount.incrementAndGet();
User user = userProvider.get();
System.out.println("Connection failed for " + user + ": " + e.getMessage());
System.out.println("Failure count: " + failureCount.incrementAndGet());
}
最佳实践
1.尽量注入不可变对象
如果可以,我们使用构造方法来注入不可变的对象,它们简单,易于分享,可以被组合。
public class RealPaymentService implements PaymentService {
private final PaymentQueue paymentQueue;
private final Notifier notifier;
@Inject
RealPaymentRequestService(
PaymentQueue paymentQueue,
Notifier notifier) {
this.paymentQueue = paymentQueue;
this.notifier = notifier;
}
...
2.仅注入直接依赖的对象
避免注入一个对象,仅仅是为了使用它获得另一个对象。
public class ShowBudgets {
private final Account account;
@Inject
ShowBudgets(Customer customer) {
account = customer.getPurchasingAccount();
}
更好的方法是,在Module中使用@Provides 通过Customer创建一个Account对象
public class CustomersModule extends AbstractModule {
@Override public void configure() {
...
}
@Provides
Account providePurchasingAccount(Customer customer) {
return customer.getPurchasingAccount();
}
这样,需要注入的地方代码会更简单
public class ShowBudgets {
private final Account account;
@Inject
ShowBudgets(Account account) {
this.account = account;
}
3.解决循环依赖
下面这样的就是循环依赖,Store -> Boss -> Clerk -> Store ...
public class Store {
private final Boss boss;
//...
@Inject public Store(Boss boss) {
this.boss = boss;
//...
}
public void incomingCustomer(Customer customer) {...}
public Customer getNextCustomer() {...}
}
public class Boss {
private final Clerk clerk;
@Inject public Boss(Clerk clerk) {
this.clerk = clerk;
}
}
public class Clerk {
private final Store shop;
@Inject Clerk(Store shop) {
this.shop = shop;
}
void doSale() {
Customer sucker = shop.getNextCustomer();
//...
}
}
文档里有解决的办法。https://github.com/google/guice/wiki/CyclicDependencies
4.避免在Module写入具体的逻辑
public class FooModule {
private final String fooServer;
public FooModule() {
this(null);
}
public FooModule(@Nullable String fooServer) {
this.fooServer = fooServer;
}
@Override protected void configure() {
if (fooServer != null) {
bind(String.class).annotatedWith(named("fooServer")).toInstance(fooServer);
bind(FooService.class).to(RemoteFooService.class);
} else {
bind(FooService.class).to(InMemoryFooService.class);
}
}
}
解决方法是将FooModule分成RemoteFooModule 和 InMemoryFooModule。
Google Guice学习的更多相关文章
- Guice学习(一)
Guice学习(一) Guice是Google开发的一个轻量级依赖注入框架(IOC).Guice非常小而且快,功能类似与Spring,但效率上网上文档显示是它的100倍,而且还提供对Servlet,A ...
- jdbc框架 commons-dbutils+google guice+servlet 实现一个例子
最近闲着无聊,于是看了一下jdbc框架 commons-dbutils与注入google guice. 我就简单的封装了一下代码,效率还是可以的.... jdbc+google guice+servl ...
- [Tensorflow实战Google深度学习框架]笔记4
本系列为Tensorflow实战Google深度学习框架知识笔记,仅为博主看书过程中觉得较为重要的知识点,简单摘要下来,内容较为零散,请见谅. 2017-11-06 [第五章] MNIST数字识别问题 ...
- Reading | 《TensorFlow:实战Google深度学习框架》
目录 三.TensorFlow入门 1. TensorFlow计算模型--计算图 I. 计算图的概念 II. 计算图的使用 2.TensorFlow数据类型--张量 I. 张量的概念 II. 张量的使 ...
- 依赖注入框架Google Guice 对象图
GettingStarted · google/guice Wiki https://github.com/google/guice/wiki/GettingStarted sameb edited ...
- 1 如何使用pb文件保存和恢复模型进行迁移学习(学习Tensorflow 实战google深度学习框架)
学习过程是Tensorflow 实战google深度学习框架一书的第六章的迁移学习环节. 具体见我提出的问题:https://www.tensorflowers.cn/t/5314 参考https:/ ...
- Google Guice 之绑定1
绑定和依赖注入区别 绑定,使用时 需要通过 injector 显示获取 依赖注入,只需要显示获取主类,他的依赖是通过@Injector 和 绑定关系 隐式注入的 http://blog.csdn.ne ...
- google guice
1 google guice是什么 google guice是一个轻量的DI容器. 2 guice和spring对比 spring的配置放在xm文件中,guice的配置放在Module中. guice ...
- 【书评】【不推荐】《TensorFlow:实战Google深度学习框架》(第2版)
参考书 <TensorFlow:实战Google深度学习框架>(第2版) 这本书我老老实实从头到尾看了一遍(实际上是看到第9章,刚看完,后面的实在看不下去了,但还是会坚持看的),所有的代码 ...
随机推荐
- Golang测试技术
本篇文章内容来源于Golang核心开发组成员Andrew Gerrand在Google I/O 2014的一次主题分享“Testing Techniques”,即介绍使用Golang开发 时会使用到的 ...
- 左偏树初步 bzoj2809 & bzoj4003
看着百度文库学习了一个. 总的来说,左偏树这个可并堆满足 堆的性质 和 左偏 性质. bzoj2809: [Apio2012]dispatching 把每个忍者先放到节点上,然后从下往上合并,假设到了 ...
- 《Web接口开发与自动化测试 -- 基于Python语言》 ---前言
前 言 本书的原型是我整理一份Django学习文档,从事软件测试工作的这六.七年来,一直有整理学习资料的习惯,这种学习理解再输出的方式对我非常受用,博客和文档是我主要的输出形式,这些输出同时也帮 ...
- 英文版Ubuntu安装配置搜狗拼音输入法
下载搜狗输入法 1 进入搜狗输入法官网,进入上面导航兰的 "输入法Linux版" 2 根据你安装的ubuntu是32位还是64位下载 END ubuntu安装搜狗输入法 1 进 ...
- iOS 使用 github
1. 创建 github 账号 登陆官网 https://github.com 进行创建. 2. 创建 github 仓库 3. 添加Pods依赖库所需文件 4. github 之 下载历史版本 5. ...
- 网站环境apache + php + mysql 的XAMPP,如何实现一个服务器上配置多个网站?
xampp 是一个非常方便的本地 apache + php + mysql 的调试环境,在本地安装测试 WordPress 等各种博客.论坛程序非常方便.今天我们来给大家介绍一下,如何使用 XAMPP ...
- 开始Java学习(Java之负基础实战)
开发平台: JavaSE:java标准平台,一般用于桌面程序开发 JavaEE:开发web(如网站+Sping) JavaME:开发移动应用 开发环境: JVM:跨平台核心. JRE:java运行时, ...
- WEB 开发者应该具备的 6 大技能?
1. 界面和用户体验 注意,浏览器的实现标准是不一致的,请确保你的网站能够兼容所有主流的浏览器.最少需要测试的有 Gecko 引擎 (Firefox),WebKit引擎(Safari以及一些手机浏览器 ...
- java me 旋转的X案例
package com.xushouwei.cn; import javax.microedition.lcdui.Command;import javax.microedition.lcdui.Co ...
- Java经典案例之-判断质数(素数)
/** * 描述:任意输入两个数n,m(n<m)判断n-m之间有多少个素数,并输出所有素数. * 分析:素数即质数,除1和本身之外,不能被其他自然数整除的数. * 判断素数的方法为:用一个数分别 ...