Guice 依赖绑定
Guice 依赖绑定
连接绑定(Linked Bingdings)
连接绑定是 Guice 最基本的一种绑定方式。这种绑定方式我们需要在自己定义的 Module 的 configure() 中编写绑定。如下所示:
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(Animal.class).to(Cat.class);
}
}
现在当调用 injector.getInstance(Animal.class) 时,就会返回一个 Cat 对象。
连接绑定也可以组成链式,如下:
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(Animal.class).to(Cat.class);
bind(Cat.class).to(PersianCat.class);
}
}
此时
注解绑定(Binding Annotations)
某些时候我们的一个接口可能有很多的实现,而此时我们在代码的某个地方想让这个接口绑定其中的某体格实现,这个时候直接使用连接绑定就不行了。
此时我们可以使用注解(Annotation)来绑定,我们可以使用自己定义的注解,举例:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface Persian {}
这个注解中需要主要的是 @BindingAnnotation 这个地方,这是由 Guice 提供的,来标识这个注解就是用来标识绑定的,我们也可以称其为绑定注解(Binging Annotation)。当一个对象被多个绑定注解所标识时,Guice 就会报错
@Inject
@Persian
private Cat cat;
我们仍然需要指定绑定关系,如下:
bind(Cat.class)
.annotatedWith(Persian.class)
.to(PersianCat.class);
其实,如果没有什么特殊需求的话,Guice 已经为我们提供了一种默认的注解来辅助我们进行对象绑定,@Named。仍然以上述例子来说明:
@Inject
@Named("persian")
private Cat cat;
此时绑定关系可以这样写:
bind(Cat.class)
.annotatedWith(Names.named("persian"))
.to(PersianCat.class);
实例绑定(Instance Bindings)
顾名思义,直接使用实例而来进行绑定。通常这种绑定作用于没有什么依赖和实现的对象上。
最普遍的应用大概就是一些参数变量的绑定了,直接 Copy 官方文档的代码:
bind(String.class)
.annotatedWith(Names.named("JDBC URL"))
.toInstance("jdbc:mysql://localhost/pizza");
bind(Integer.class)
.annotatedWith(Names.named("login timeout seconds"))
.toInstance(10);
如果实例过于复杂,就不要使用这样的方式绑定,因为这些代码写在 Module 的 configure() 中,会拖慢程序的启动。稍后会说到,可以使用 @Provides 来代替。
@Provides 方法
当需要某种类型的对象时,就可以使用 @Provides 方法。这类方法必须定义在 Module 中,且用 @Provides 标识,如下:
public class AppModule extends AbstractModule {
protected void configure() {}
@Provides
PersianCat providePersianCat() {
PersianCat persianCat = new PersianCat();
persianCat.setName("Foo");
return persianCat;
}
}
这时当注入 PersianCat 类型对象时,就会从 providePersianCat() 方法中生成。
@Provides 方法也可以添加注解,这里就直接贴官方代码了,不做赘述:
@Provides @PayPal
CreditCardProcessor providePayPalCreditCardProcessor(@Named("PayPal API key") String apiKey) {
PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
processor.setApiKey(apiKey);
return processor;
}
Provider 绑定(Provider Bindings)
当使用了太多 @Provides 方法绑定之后,Module 就会显得臃肿不堪。这时可以试着将这些方法从 Module 中剥离出来,只要实现 Guice 提供的 Provider 的接口即可。
public interface Provider<T> {
T get();
}
Provider 接口只有一个 get() 方法,其实很简单。直接把上述代码移至此处。
public class PersianCatProvider implements Provider<PersianCat> {
public PersianCat get() {
PersianCat persianCat = new PersianCat();
persianCat.setName("Foo");
return persianCat;
}
}
最后如果需要,可以指定类型绑定到 Provider:
bind(Cat.class).toProvider(PersianCatProvider.class);
构造方法绑定(Constructor Bindings)
有时候当绑定对象有多个构造方法时,我们可能需要指定某一个构造方法,这时可以使用构造方法绑定来达到目的。如下:
try {
bind(PersianCat.class).toConstructor(PersianCat.class.getConstructor(String.class));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
需要注意的是,这种绑定方式需要捕获异常。
@ImplementedBy 与 @ProvidedBy
@ImplementedBy 注解用于简化绑定配置,通常用于指定默认的实现类型。最常用的场景在于编写 Dao 或者 Service 时,指定 Interface 的实现类。直接给出官方示例:
@ImplementedBy(PayPalCreditCardProcessor.class)
public interface CreditCardProcessor {
ChargeResult charge(String amount, CreditCard creditCard) throws UnreachableException;
}
等价于:
bind(CreditCardProcessor.class).to(PayPalCreditCardProcessor.class);
@ProvidedBy 也是顾名思义:
@ProvidedBy(DatabaseTransactionLogProvider.class)
public interface TransactionLog {
void logConnectException(UnreachableException e);
void logChargeResult(ChargeResult result);
}
等价于
bind(TransactionLog.class).toProvider(DatabaseTransactionLogProvider.class);
Guice 依赖绑定的更多相关文章
- spring揭秘 读书笔记 二 BeanFactory的对象注册与依赖绑定
本文是王福强所著<<spring揭秘>>一书的读书笔记 我们前面就说过,Spring的IoC容器时一个IoC Service Provider,而且IoC Service Pr ...
- Spring中BeanFactory的对象注册与依赖绑定方式
概念 BeanFactory是spring的基础类型IOC容器,提供完整的IOC服务支持 默认采用延迟初始化策略,当客户端对象访问受管对象时,才对其进行初始化和依赖注入 理解 BeanFactory将 ...
- spring揭秘 读书笔记 二 BeanFactory的对象注冊与依赖绑定
本文是王福强所著<<spring揭秘>>一书的读书笔记 我们前面就说过,Spring的IoC容器时一个IoC Service Provider,并且IoC Service Pr ...
- Google Guice 之绑定1
绑定和依赖注入区别 绑定,使用时 需要通过 injector 显示获取 依赖注入,只需要显示获取主类,他的依赖是通过@Injector 和 绑定关系 隐式注入的 http://blog.csdn.ne ...
- Elasticsearch源码分析 | 单节点的启动和关闭
本文主要简要介绍Elasticsearch单节点的启动和关闭流程.Elasticsearch版本:6.3.2 相关文章 1.Google Guice 快速入门 2.Elasticsearch 中的 G ...
- 【翻译】 Guice 动机——依赖注入的动机
原文链接 动机 将所有的内容连接在一起时应用开发的一个单调乏味的部分.有几种方式来将数据.服务.presetntation类连接到一起.为了对比这些方法,我将为披萨订购网站编写账单代码: public ...
- java轻量级IOC框架Guice
Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...
- Google Guice结合模式
于Guice于,喷油器装配工作是一个对象图,当请求类型实例,喷油器根据推断对象如何映射到创建的实例.解决依赖.要确定如何解决的依赖就需要配置喷油器结合的方式. 要创建绑定(Binding)对象,能够继 ...
- google guice
1 google guice是什么 google guice是一个轻量的DI容器. 2 guice和spring对比 spring的配置放在xm文件中,guice的配置放在Module中. guice ...
随机推荐
- redis 启动停止脚本
redis 启动停止脚本,该redis需要密码登录,如没有密码,去掉stop函数里的 -a #!/bin/sh # #chkconfig: 2345 80 90 # Simple Redis init ...
- 学习windows编程 day4 之 绘制随机矩形和peekMessage
#include <windows.h> #include <strsafe.h> LRESULT CALLBACK WndProc(HWND hwnd, UINT messa ...
- javascript 实现手风琴特效
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- C# 面向对象的new关键字的使用
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- JavaScript之Array/数组小结
MDN-Array的属性/方法:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Arr ...
- 第19月第2天 cellForItemAtIndexPath 返回空
1. 动画需要获取当前的 Cell ,下面的调用在 viewDidLoad 中,有时候返回 nil,有时候成功. UICollectionView *cell = (UICollectionView* ...
- 第16月第15天 glut
1. https://tokoik.github.io/opengl/libglut.html https://github.com/wistaria/wxtest/tree/master/C htt ...
- react框架的状态管理
安装: cnpm install --save redux cnpm install --save react-redux 安装好后导入模块内容: impor {createStore} from ...
- VMware12虚拟机中Ubuntu16.04安装CPU版本Caffe
首先,可以自行下载VMware12进行安装,基本上都是直接点击‘下一步’直到安装完成,这里重点讲一下Ubuntu16及Caffe的安装步骤 第一步: 下载Ubuntu16.04版本的文件,这里给出链接 ...
- Spring使用注解和struts集成