出处:http://www.cnblogs.com/whitewolf/p/4185908.html

Guice是由Google大牛Bob lee开发的一款绝对轻量级的java IoC容器。其优势在于:

  1. 速度快,号称比spring快100倍。
  2. 无外部配置(如需要使用外部可以可以选用Guice的扩展包),完全基于annotation特性,支持重构,代码静态检查。
  3. 简单,快速,基本没有学习成本。

Guice和spring各有所长,Guice更适合与嵌入式或者高性能但项目简单方案,如OSGI容器,spring更适合大型项目组织。

注入方式

在我们谈到IOC框架,首先我们的话题将是构造,属性以及函数注入方式,Guice的实现只需要在构造函数,字段,或者注入函数上标注@Inject,如:

构造注入

  1. public class OrderServiceImpl implements OrderService {
  2. private ItemService itemService;
  3. private PriceService priceService;
  4. @Inject
  5. public OrderServiceImpl(ItemService itemService, PriceService priceService) {
  6. this.itemService = itemService;
  7. this.priceService = priceService;
  8. }
  9. ...
  10. }

属性注入

  1. public class OrderServiceImpl implements OrderService {
  2. private ItemService itemService;
  3. private PriceService priceService;
  4. @Inject
  5. public void init(ItemService itemService, PriceService priceService) {
  6. this.itemService = itemService;
  7. this.priceService = priceService;
  8. }
  9. ...
  10. }

函数(setter)注入

  1. public class OrderServiceImpl implements OrderService {
  2. private ItemService itemService;
  3. private PriceService priceService;
  4. @Inject
  5. public void setItemService(ItemService itemService) {
  6. this.itemService = itemService;
  7. }
  8. @Inject
  9. public void setPriceService(PriceService priceService) {
  10. this.priceService = priceService;
  11. }
  12. ...
  13. }

Module依赖注册

Guice提供依赖配置类,需要继承至AbstractModule,实现configure方法。在configure方法中我们可以用Binder配置依赖。

Binder利用链式形成一套独具语义的DSL,如:

  • 基本配置:binder.bind(serviceClass).to(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
  • 无base类、接口配置:binder.bind(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
  • service实例配置:binder.bind(serviceClass).toInstance(servieInstance).in(Scopes.[SINGLETON | NO_SCOPE]);
  • 多个实例按名注入:binder.bind(serviceClass).annotatedWith(Names.named(“name”)).to(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
  • 运行时注入:利用@Provides标注注入方法,相当于spring的@Bean。
  • @ImplementedBy:或者在实现接口之上标注@ImplementedBy指定其实现类。这种方式有点反OO设计,抽象不该知道其实现类。

对于上面的配置在注入的方式仅仅需要@Inject标注,但对于按名注入需要在参数前边加入@Named标注,如:

  1. public void configure() {
  2. final Binder binder = binder();
  3. //TODO: bind named instance;
  4. binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);
  5. binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);
  6. }
  7. @Inject
  8. public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,
  9. @Named("impl2") NamedService nameService2) {
  10. }

Guice也可以利用@Provides标注注入方法来运行时注入:如

  1. @Provides
  2. public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,
  3. @Named("impl2") NamedService nameService2) {
  4. final ArrayList<NamedService> list = new ArrayList<NamedService>();
  5. list.add(nameService1);
  6. list.add(nameService2);
  7. return list;
  8. }

Guice实例

下面是一个Guice module的实例代码:包含大部分常用依赖配置方式。更多代码参见github.

  1. package com.github.greengerong.app;
  2. /**
  3. * ***************************************
  4. * *
  5. * Auth: green gerong *
  6. * Date: 2014 *
  7. * blog: http://greengerong.github.io/ *
  8. * github: https://github.com/greengerong *
  9. * *
  10. * ****************************************
  11. */
  12. public class AppModule extends AbstractModule {
  13. private static final Logger LOGGER = LoggerFactory.getLogger(AppModule.class);
  14. private final BundleContext bundleContext;
  15. public AppModule(BundleContext bundleContext) {
  16. this.bundleContext = bundleContext;
  17. LOGGER.info(String.format("enter app module with: %s", bundleContext));
  18. }
  19. @Override
  20. public void configure() {
  21. final Binder binder = binder();
  22. //TODO: bind interface
  23. binder.bind(ItemService.class).to(ItemServiceImpl.class).in(SINGLETON);
  24. binder.bind(OrderService.class).to(OrderServiceImpl.class).in(SINGLETON);
  25. //TODO: bind self class(without interface or base class)
  26. binder.bind(PriceService.class).in(Scopes.SINGLETON);
  27. //TODO: bind instance not class.
  28. binder.bind(RuntimeService.class).toInstance(new RuntimeService());
  29. //TODO: bind named instance;
  30. binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);
  31. binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);
  32. }
  33. @Provides
  34. public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,
  35. @Named("impl2") NamedService nameService2) {
  36. final ArrayList<NamedService> list = new ArrayList<NamedService>();
  37. list.add(nameService1);
  38. list.add(nameService2);
  39. return list;
  40. }
  41. }

Guice的使用

对于Guice的使用则比较简单,利用利用Guice module初始化Guice创建其injector,如:

  1. Injector injector = Guice.createInjector(new AppModule(bundleContext));

这里可以传入多个module,我们可以利用module分离领域依赖。

Guice api方法:

  1. public static Injector createInjector(Module... modules)
  2. public static Injector createInjector(Iterable<? extends Module> modules)
  3. public static Injector createInjector(Stage stage, Module... modules)
  4. public static Injector createInjector(Stage stage, Iterable<? extends Module> modules)

Guice同时也支持不同Region配置,上面的State重载,state支持 TOOL,DEVELOPMENT,PRODUCTION选项;默认为DEVELOPMENT环境。

后续

本文Guice更全的demo代码请参见github.

Guice还有很多的扩展如AOP,同一个服务多个实例注入set,map,OSGI,UOW等扩展,请参见Guice wiki.

java轻量级IOC框架Guice(转)的更多相关文章

  1. java轻量级IOC框架Guice

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

  2. 轻量级IOC框架Guice

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

  3. 轻量级IOC框架:Ninject

    Ninject 学习杂记 - liucy 时间2014-03-08 00:26:00 博客园-所有随笔区原文  http://www.cnblogs.com/liucy1898/p/3587455.h ...

  4. 轻量级DI框架Guice使用详解

    背景 在日常写一些小工具或者小项目的时候,有依赖管理和依赖注入的需求,但是Spring(Boot)体系作为DI框架过于重量级,于是需要调研一款微型的DI框架.Guice是Google出品的一款轻量级的 ...

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

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

  6. 轻量级IoC框架Ninject.NET搭建

    说在之前的话 IOC的概念相信大家比较熟悉了,习惯性称之为依赖注入或控制反转,园子里对基于MVC平台IOC设计模式已经相当多了,但大家都只知道应该怎么应用一个IOC模式,比如Ninject, Unit ...

  7. 轻量级IOC框架SwiftSuspenders

    该框架的1.6版本位于https://github.com/tschneidereit/SwiftSuspenders/blob/the-past/,现在已经出了重新架构的2.0版本,所以我决定先研究 ...

  8. 轻量级IOC框架:Ninject (下)

    一,创建依赖链(Chains of Dependency) 当我们向Ninject请求创建一个类型时,Ninject会去检查该类型和其他类型之间的耦合关系.如果有额外的依赖,Ninject也会解析它们 ...

  9. cache4j轻量级java内存缓存框架,实现FIFO、LRU、TwoQueues缓存模型

    简介 cache4j是一款轻量级java内存缓存框架,实现FIFO.LRU.TwoQueues缓存模型,使用非常方便. cache4j为java开发者提供一种更加轻便的内存缓存方案,杀鸡焉用EhCac ...

随机推荐

  1. 1095 Cars on Campus

    题意:给出N量车的车牌号,进出的时间,进/出状态.然后给出若干个查询,要求计算在每一查询时刻校园内停着的汽车数量,最后输出这一天中停放时间最长的车辆(若车不止一辆,则按字典序输出)以及停放时间.注:查 ...

  2. 第十二章 Ganglia监控Hadoop及Hbase集群性能(安装配置)

    1 Ganglia简介 Ganglia 是 UC Berkeley 发起的一个开源监视项目,设计用于测量数以千计的节点.每台计算机都运行一个收集和发送度量数据(如处理器速度.内存使用量等)的名为 gm ...

  3. 如何混编c++

    1.  如何混编c++ 用 Xcode4 创建一个 工程,如果在任意一个文件AAA.h的头部加入 #include<string> using  namespace  std; 编译运行, ...

  4. 浅谈PHP面向对象编程(八、多态)

    8.0  多态 在设计一个成员方法时,通常希望该方法具备一定的通用性.例如要实现一个动物叫的方法,由于每个动物的叫声是不同的,因此可以在方法中接收-个动物类型的参数的对象当传人猫类对象时就发出猫类的叫 ...

  5. 仅用CSS3创建h5预加载旋转圈

    <head> <meta charset="UTF-8"> <title></title> <style type=" ...

  6. Vue语法

    第一个Vue示例: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  7. redis存session问题测试内容

    转至元数据起始   官网,现网由于是双节点,session是存储在redis作为共享的. +1是单节点.目前是存储成文件的 本次的问题根源是 由于 session是存储在redis,所造成的. 所以需 ...

  8. t讯src的一点小秘密

    1.腾讯网首页发表评论未做限制 风险url:http://coral.qq.com/2774166934 使用burp的intruder模块生成payload 未做任何限制导致可批量提交大量的评论…… ...

  9. JS比较两个数组是否相等 是否拥有相同元素

    Javascript怎么比较两个数组是否相同?JS怎么比较两个数组是否有完全相同的元素?Javascript不能直接用==或者===来判断两个数组是否相等,无论是相等还是全等都不行,以下两行JS代码都 ...

  10. 【296】Python 默认 IDE 修改

    参考:找回Python IDLE Shell里的历史命令(用上下键翻历史命令怎么不好用了呢?) 参考:Python IDLE快捷键一览 参考:Python IDLE 自动提示功能 参考:如何让pyth ...