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

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

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

注入方式

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

构造注入

public class OrderServiceImpl implements OrderService {private ItemService itemService;private PriceService priceService;@Injectpublic OrderServiceImpl(ItemService itemService, PriceService priceService) {this.itemService = itemService;this.priceService = priceService;}...
}

属性注入

public class OrderServiceImpl implements OrderService {private ItemService itemService;private PriceService priceService;@Injectpublic void init(ItemService itemService, PriceService priceService) {this.itemService = itemService;this.priceService = priceService;}...
}

函数(setter)注入

public class OrderServiceImpl implements OrderService {private ItemService itemService;private PriceService priceService;@Injectpublic void setItemService(ItemService itemService) {this.itemService = itemService;}@Injectpublic void setPriceService(PriceService priceService) {this.priceService = priceService;} ...
}

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标注,如:

public void configure() {final Binder binder = binder();//TODO: bind named instance;binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);
}@Inject
public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,@Named("impl2") NamedService nameService2) {
}

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

   @Providespublic List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,@Named("impl2") NamedService nameService2) {final ArrayList<NamedService> list = new ArrayList<NamedService>();list.add(nameService1);list.add(nameService2);return list;
}

Guice实例

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

package com.github.greengerong.app;/*** **************************************** ** Auth: green gerong                     ** Date: 2014                             ** blog: http://greengerong.github.io/    ** github: https://github.com/greengerong ** ** *****************************************/
public class AppModule extends AbstractModule {private static final Logger LOGGER = LoggerFactory.getLogger(AppModule.class);private final BundleContext bundleContext;public AppModule(BundleContext bundleContext) {this.bundleContext = bundleContext;LOGGER.info(String.format("enter app module with: %s", bundleContext));}@Overridepublic void configure() {final Binder binder = binder();//TODO: bind interfacebinder.bind(ItemService.class).to(ItemServiceImpl.class).in(SINGLETON);binder.bind(OrderService.class).to(OrderServiceImpl.class).in(SINGLETON);//TODO: bind self class(without interface or base class)binder.bind(PriceService.class).in(Scopes.SINGLETON);//TODO: bind instance not class.binder.bind(RuntimeService.class).toInstance(new RuntimeService());//TODO: bind named instance;binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);}@Providespublic List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,@Named("impl2") NamedService nameService2) {final ArrayList<NamedService> list = new ArrayList<NamedService>();list.add(nameService1);list.add(nameService2);return list;}
}

Guice的使用

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

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

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

Guice api方法:

public static Injector createInjector(Module... modules) public static Injector createInjector(Iterable<? extends Module> modules) public static Injector createInjector(Stage stage, Module... modules)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. .NET的轻量级IOC框架芮双随笔

    面向对象的设计的重用性一直是他的一个重要特性,为了有效定义这一特性,又引申出面向对象设计的几个原则:高内聚.低耦合.功能单一.优先使用聚合.面向接口编程等.依赖这些原则和前人的经验,又发展出形形色色的 ...

  2. java 轻量级 web 框架,Fast-FrameWork

    软件简介 Fast-FrameWork 轻量级 Java Web 框架 基于 JDK 8 规范 基于 Servlet 3.0 规范 零配置 REST 服务接口 基于 JSON 传输 目前提供 MVC ...

  3. 在WCF中使用Ninject轻量级IOC框架 之 SOAP风格服务

    最近学习MVC 看到很多文章都用了Ninject框架进行解耦,就考虑是否能用在平时写的WCF服务中,因为毕竟目前还是总要写服务的--蛋疼ing-- 传送门: Ninject框架官网: http://w ...

  4. Google的IOC框架: GUICE

    http://java.csdn.net/subject/gspring.html google的触角真是无所不在,今天刚用上了谷歌拼音输入法,紧接着又看到一个GUICE,下载了user guide来 ...

  5. Java 轻量级框架Spring曝出0day漏洞

    首语 3月29日,Spring框架曝出RCE 0day漏洞.已经证实由于 SerializationUtils#deserialize 基于 Java 的序列化机制,可导致远程代码执行 (RCE),使 ...

  6. python ioc框架_IOC 实现原理

    IOC 也就是"控制反转"了,不过更流行的叫法是"依赖注入"(DI - Dependency Injection).听起来挺高深,其实实现起来并不复杂.下面就看 ...

  7. java 轻量级 job_oxygen: 一个轻量级Java框架,包含ioc、aop、config、cache、job、Jdbc、web等...

    oxygen 轻量级Java框架 介绍 一个轻量级Java框架 oxygen-core 配置管理,支持${attrs.key:defaultValue}表达式获取配置 加解密管理,提供加解密服务内置基 ...

  8. java轻量级框架_轻量级的Java 开发框架 Spring

    Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development a ...

  9. java持久化框架_众里寻他千百度-- 轻量级持久化框架-java-火龙果软件工程

    起了一个比较文艺的标题,但是仍然感觉不能 表达出接下来这个工具的文雅. 虽然这个库是前几个月写的了,但是经过了近期小项目的考验,愈发觉得这款轻量级的库应该被更多的开发者所知晓,于是"臭不要脸 ...

最新文章

  1. 基于css3 transform实现散乱的照片排列
  2. [Swift]NSString、NSData、Base64互转
  3. SAP PM预防性维护
  4. 捅破窗户纸:如何从过程到对象—For金色的海洋以及所有为面向对象而困惑的Tx...
  5. java数组随机排序_JAVA 生成随机数数组,并排序输出
  6. Torchvision目标检测模型训练过程记录
  7. 关于arguments
  8. springboot中使用lua脚本+aop作限流访问案例代码
  9. 高数复习9.13 函数与极限
  10. 【LeetCode笔记】54. 螺旋矩阵(Java、迭代、递归)
  11. 【转载】为了我们的SZ4J代码
  12. 用Python破解数学教育
  13. STM32CubeMX 配置STM32F407 实现HAL库延时微妙方案
  14. 微信公众平台消息接口开发(26)从Hello2BizUser文本到subscribe事件
  15. 哪一个瞬间,点燃了你的离职决心?
  16. 北大中文核心期刊目录(2004年版)全文
  17. SVN客户端详细说明
  18. kindeditor php 漏洞,KindEditor漏洞、优化以及漏洞、BUG修复方案汇总
  19. 亲测:华为老爷机安装谷歌框架
  20. cad2019菜单栏怎么调出来_cad怎样调出菜单栏(cad2016工具栏怎么调出来)

热门文章

  1. 只需2.5W功耗,就能达到5TOPS算力!地平线新一代AIoT芯片「旭日3」发布
  2. 矩阵元算法科学家谢翔: Rosetta如何连接隐私计算与AI?
  3. 马斯克的星际飞船首次起飞测试成功!起跳150米后平稳着陆,“火星在望”
  4. 「仅凭照片就能判断一个人是否犯罪」?这样的研究能发表,LeCun、MIT谷歌等机构的1700名研究者怒了...
  5. 这引人联想的机械右手!玩转魔方,灵活不输人类,OpenAI:前所未有
  6. 全球最大AI商业展会开幕,这家老牌巨头担当中国唯一代表
  7. 网红送餐无人车被指用人冒充AI始末:没有人工,就没有智能
  8. 33 个 JavaScript 核心概念系列(三): 显式 (名义) 与 隐式 (鸭子)类型转换
  9. ansible 介绍
  10. javascript 内部函数的定义及调用