Guice之IOC教程
Guice
在上一篇博客中, 我们讲解了Spring中的IOC示例与实现, 本文着重介绍Guice注入以及与Spring中的差异.
Guice是Google开发的, 一个轻量级的依赖注入框架, 跟Spring最大的区别在于脱离xml配置,
大量使用Annotation来实现注入, 支持属性, 构造器, setter等多种方式注入对象.
Guice 3.0支持 jdk 1.6, 如果运行报错ClassNotFoundException: javax.inject.Provider, 则需要导入javax.inject包.
Module容器
Guice中容器即Module, 用于绑定接口 : 实现类, 类似于Spring中的applicationContext.xml.
Module像是一个Map,根据一个Key获取其Value,清楚明了的逻辑.
以下代码实现了一个简单的注入
Injector ij = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.bind(TestService.class).to(ServiceImpl.class);
}
});
ij.getInstance(TestService.class).test();
支持绕过Module, 用默认配置, 直接实例化对象, 不过没啥意义, 除非要用容器做aop
Injector ij2 = Guice.createInjector();
ij2.getInstance(ServiceImpl.class).test();
当然也可以使用注解的方式来声明接口的实现类, 然后Injector 从接口中获取对象,
意义也不大, 因为实际业务中, 接口可能在上层包里, 无法直接调用实现类.
@ImplementedBy(ServiceImpl.class)
public interface TestService { void test();
} --------------------------------------- Injector ij3 = Guice.createInjector();
10 ij3.getInstance(TestService.class).test();
@Inject属性注入
public class GuiceObjectDemo {
@Inject
private TestService service1;
@Inject
private TestService service2;
---------------------------------------
GuiceObjectDemo demo = Guice.createInjector().getInstance(GuiceObjectDemo.class);
System.out.println(demo.getService());
System.out.println(demo.getService2());
属性注入的时候, 必须通过Guice.createInjector().getInstance(GuiceObjectDemo.class);来获取实现类, 如果直接new的话, 会inject失败, 打印出两个null.
这是因为如果对象不属于Guice托管, 那么他也无法得到Guice注入.
如果一定要new GuiceObjectDemo()呢? 没关系, 还有另外一种写法可以满足.
GuiceObjectDemo demo1 = new GuiceObjectDemo();
Guice.createInjector().injectMembers(demo1);
System.out.println(demo1.getService());
静态属性注入
调用binder.requestStaticInjection
Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.requestStaticInjection(GuiceObjectDemo.class);
}
});
System.out.println(GuiceObjectDemo.getService3());
普通属性也可以通过该方法注入, 只要把binder那边改成requestInjection即可.
构造函数注入
@Inject
public GuiceObjectDemo(TestService service1, TestService service2) {
this.service1 = service1;
this.service2 = service2;
}
构造函数会自动注入多个参数, 因此只要写一个@Inject即可.
如果有多个构造函数, 只能在一个构造函数上加Inject, 不然会报错
has more than one constructor annotated with @Inject
同理Setter注入, 只要在setXX方法上加上@Inject标签即可实现赋值.
动态参数注入
这个稍微麻烦一点, 需要引入guice-assistedinject, 利用FactoryModuleBuilder构造一个factory实行注入.
实际业务场景中, 大部分构造函数的参数是动态从外部传递进来的, 并不是直接new出来的.
public class ServiceImpl implements TestService{
private String member;
@Inject
public ServiceImpl(@Assisted String member) {
// 利用Assisted注解, 动态注入参数
this.member = member;
}
public void setMember(String member) {
this.member = member;
}
@Override
public String toString() {
return "ServiceImpl Memeber: " + member;
}
}
---------------------------------------
public interface TestService {
}
---------------------------------------
public interface PageFactory {
ReportPageProvider createReportPage(ResultReport report);
}
---------------------------------------
public class IOCDemo {
public static void main(String[] args){
Module module = new com.fr.third.inject.Module() {
@Override
public void configure(Binder binder) {
binder.install(new FactoryModuleBuilder()
.implement(TestService.class, ServiceImpl.class)
.build(ImplFactory.class)
);
}
};
Injector injector = Guice.createInjector(module);
ImplFactory factory = injector.getInstance(ImplFactory.class);
TestService impl = factory.create("neil123");
System.out.println(impl);
}
}
有多个实现类的接口
此时通过上文直接写单个@Inject或者Module都无法实现, 需要引入自定义注解, 或者Names方法.
public class GuiceObjectDemo {
@Inject
@Named("A")
private TestService service1;
@Inject
@Named("B")
private TestService service2;
---------------------------------------
final GuiceObjectDemo demo1 = new GuiceObjectDemo();
Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.bind(TestService.class).annotatedWith(Names.named("A")).to(ServiceImplA.class);
binder.bind(TestService.class).annotatedWith(Names.named("B")).to(ServiceImplB.class);
binder.requestInjection(demo1);
}
});
System.out.println(demo1.getService());
System.out.println(demo1.getService2());
如果不用Named注解, 则可以通过自定义注解, 其他写法都一样
binder.bind(TestService.class).annotatedWith(ImplA.class).to(ServiceImplA.class);
binder.bind(TestService.class).annotatedWith(ImplB.class).to(ServiceImplB.class);
Provider注入
其实就是类似于工厂注入, 对象不是直接new接口的实现类, 而是由工厂提供.
public class ServiceFactory implements Provider<TestService> {
@Override
public TestService get() {
return new ServiceImpl();
}
}
---------------------------------------
@ProvidedBy(ServiceFactory.class)
public interface TestService {
void test();
}
---------------------------------------
GuiceObjectDemo demo = Guice.createInjector().getInstance(GuiceObjectDemo.class);
System.out.println(demo.getService());
Scope
可以通过在impl类上加@Singleton来实现单例, 也可在module中管理
binder.bind(TestService.class).to(ServiceImpl.class).in(Scopes.SINGLETON);
默认单例模式的对象, 是在第一次使用的时候才初始化, 也可以通过设置asEagerSingleton, 注入到容器后立刻初始化.
Injector in = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
// 调用getInstance才初始化impl
binder.bind(ServiceImpl.class);
// 注入到容器后立刻初始化impl
// binder.bind(ServiceImpl.class).asEagerSingleton();
}
});
Thread.sleep(3000);
in.getInstance(ServiceImpl.class).test();
到这边就结束了, 通过上面的案例不难看出, , 相比于Spring IOC, Guice是一个非常轻量灵活的注入实现, 0 xml.
Guice之IOC教程的更多相关文章
- Guice 4.1教程
Guice是Google开发的一个开源轻量级的依赖注入框架,运行速度快,使用简单. 项目地址:https://github.com/google/guice/ 最新的版本是4.1,本文基于此版本. 0 ...
- 使用Dagger2做静态注入, 对比Guice.
Dagger 依赖注入的诉求, 这边就不重复描述了, 在上文Spring以及Guice的IOC文档中都有提及, 既然有了Guice, Google为啥还要搞个Dagger2出来重复造轮子呢? 因为使用 ...
- 轻量级IOC框架:Ninject (上)
前言 前段时间看Mvc最佳实践时,认识了一个轻量级的IOC框架:Ninject.通过google搜索发现它是一个开源项目,最新源代码地址是:http://github.com/enkari/ninje ...
- Guice总结
Guice总结 Jar包:guice-4.1.0.jar 辅包: guava-15.0.jar aopalliance-.jar javaee-api-6.0-RC2.jar Guice的IoC 两种 ...
- 58 web框架Argo代码分析
贴地址:https://github.com/58code/Argo 核心jar javax.servlet-api 3.0.1 guice 3.0 velocity 1.7 框架使用 servlet ...
- Ninject学习笔记<四>
前言 前段时间看Mvc最佳实践时,认识了一个轻量级的IOC框架:Ninject.通过google搜索发现它是一个开源项目,最新源代码地址是:http://github.com/enkari/ninje ...
- 深入浅出微服务框架dubbo(一):基础篇
一.基础篇 1.1 开篇说明 dubbo是一个分布式服务框架,致力于提供高性能透明化RPC远程调用方案,提供SOA服务治理解决方案.本文旨在将对dubbo的使用和学习总结起来,深入源码探究原理,以备今 ...
- java轻量级IOC框架Guice
Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...
- 轻量级IOC框架Guice
java轻量级IOC框架Guice Guice是由Google大牛Bob lee开发的一款绝对轻量级的java IoC容器.其优势在于: 速度快,号称比spring快100倍. 无外部配置(如需要使用 ...
随机推荐
- sqoop1.9.7安装和使用
安装1.下载sqoop1.9.7.地址: http://www.apache.org/dyn/closer.lua/sqoop/1.99.72.解压sqoop ,并配置环境变量 ~/.bash_pro ...
- zookeeper启动后的注意事项
在各节点中运行zkServer.sh start后 1.首先看进程是否存在 QuorumPeerMain. 2.查看zookeeper的运行状态 zkServer.sh status,会出现一个lea ...
- Golang源码探索(一) 编译和调试源码
GO可以说是近几年最热门的新型语言之一了, 一般人看到分布式和大数据就会想到GO, 这个系列的文章会通过研究golang的源代码来分析内部的实现原理, 和CoreCLR不同的是, golang的源代码 ...
- Java动手动脑——多态和继承
Java动手动脑——继承和多态 实验一 预估输出答案:100 200 201 202 输出结果:100 200 201 202 输出答案分析:100 创建parent类的对象,调用对象的方 ...
- OGEngine_2.x中BitmapFont加载后黑屏问题的解决办法
在我使用OGEngine_2.x进行消灭圈圈(星星)游戏的实践的时候,使用BitmapFont对自定义字体进行调用. 原文字体教程如下:http://blog.csdn.net/OrangeGame/ ...
- 非对称加密技术- RSA算法数学原理分析
非对称加密技术,在现在网络中,有非常广泛应用.加密技术更是数字货币的基础. 所谓非对称,就是指该算法需要一对密钥,使用其中一个(公钥)加密,则需要用另一个(私钥)才能解密. 但是对于其原理大部分同学应 ...
- ARM开发板链接shell
1.用网线插入开发板(最好链接路由器) 2.启动开发板(可以用U盘启动) 执行 #run bootusb 3.联网 #ifconfig eth0 up #udhcpc或者#dhclient wan # ...
- [转载] 布隆过滤器(Bloom Filter)详解
转载自http://www.cnblogs.com/haippy/archive/2012/07/13/2590351.html 布隆过滤器[1](Bloom Filter)是由布隆(Burton ...
- innobackupex: fatal error: no ‘innodb_buffer_pool_filename’解决方法
http://www.ttlsa.com/mysql/innobackupex-1-5-1-fatal-error-no-innodb_buffer_pool_filename/
- Unity3D高性能战争迷雾实现
效果图 先上效果图吧,这是为了吸引到你们的ヽ(。◕‿◕。)ノ゚ 战争迷雾效果演示图 战争调试界面演示图 由于是gif录制,为了压缩图片,帧率有点低,实际运行时,参数调整好是不会像这样一卡一顿的. 战争 ...