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教程的更多相关文章

  1. Guice 4.1教程

    Guice是Google开发的一个开源轻量级的依赖注入框架,运行速度快,使用简单. 项目地址:https://github.com/google/guice/ 最新的版本是4.1,本文基于此版本. 0 ...

  2. 使用Dagger2做静态注入, 对比Guice.

    Dagger 依赖注入的诉求, 这边就不重复描述了, 在上文Spring以及Guice的IOC文档中都有提及, 既然有了Guice, Google为啥还要搞个Dagger2出来重复造轮子呢? 因为使用 ...

  3. 轻量级IOC框架:Ninject (上)

    前言 前段时间看Mvc最佳实践时,认识了一个轻量级的IOC框架:Ninject.通过google搜索发现它是一个开源项目,最新源代码地址是:http://github.com/enkari/ninje ...

  4. Guice总结

    Guice总结 Jar包:guice-4.1.0.jar 辅包: guava-15.0.jar aopalliance-.jar javaee-api-6.0-RC2.jar Guice的IoC 两种 ...

  5. 58 web框架Argo代码分析

    贴地址:https://github.com/58code/Argo 核心jar javax.servlet-api 3.0.1 guice 3.0 velocity 1.7 框架使用 servlet ...

  6. Ninject学习笔记<四>

    前言 前段时间看Mvc最佳实践时,认识了一个轻量级的IOC框架:Ninject.通过google搜索发现它是一个开源项目,最新源代码地址是:http://github.com/enkari/ninje ...

  7. 深入浅出微服务框架dubbo(一):基础篇

    一.基础篇 1.1 开篇说明 dubbo是一个分布式服务框架,致力于提供高性能透明化RPC远程调用方案,提供SOA服务治理解决方案.本文旨在将对dubbo的使用和学习总结起来,深入源码探究原理,以备今 ...

  8. java轻量级IOC框架Guice

    Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...

  9. 轻量级IOC框架Guice

    java轻量级IOC框架Guice Guice是由Google大牛Bob lee开发的一款绝对轻量级的java IoC容器.其优势在于: 速度快,号称比spring快100倍. 无外部配置(如需要使用 ...

随机推荐

  1. Debug 运行正常,Release版本不能正常运行总结(转)

    引言      如果在您的开发过程中遇到了常见的错误,或许您的Release版本不能正常运行而Debug版本运行无误,那么我推荐您阅读本文:因为并非如您想象的那样,Release版本可以保证您的应用程 ...

  2. Just a Hook(区间set)

    Just a Hook Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  3. SSH服务详解

    第1章 SSH服务 1.1 SSH服务协议说明 SSH 是 Secure Shell Protocol 的简写,由 IETF 网络工作小组(Network Working Group )制定:在进行数 ...

  4. Datatable转换为Json

    /// <summary> /// Datatable转换为Json /// </summary> /// <param name="table"&g ...

  5. Spring+Spring MVC+MyBatis框架集成

    目录 一.新建一个基于Maven的Web项目 二.创建数据库与表 三.添加依赖包 四.新建POJO实体层 五.新建MyBatis SQL映射层 六.JUnit测试数据访问 七.完成Spring整合My ...

  6. 快速自检电脑是否被黑客入侵过(Windows版)

    我们经常会感觉电脑行为有点奇怪, 比如总是打开莫名其妙的网站, 或者偶尔变卡(网络/CPU), 似乎自己"中毒"了, 但X60安全卫士或者X讯电脑管家扫描之后又说你电脑" ...

  7. [转载] ZooKeeper简介

    转载自http://blog.csdn.net/kobejayandy/article/details/17738435 一.      Paxos 基于消息传递通信模型的分布式系统,不可避免的会发生 ...

  8. ssh相关原理学习与常见错误总结

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  9. Runtime的理解与实践

    Runtime是什么?见名知意,其概念无非就是"因为 Objective-C 是一门动态语言,所以它需要一个运行时系统--这就是 Runtime 系统"云云.对博主这种菜鸟而言,R ...

  10. canvas图表(3) - 饼图

    原文地址:canvas图表(3) - 饼图 这几天把canvas图表都优化了下,动画效果更加出色了,可以说很逼近echart了.刚刚写完的饼图,非常好的实现了既定的功能,交互的动画效果也是很棒的. 效 ...