轻量级IOC框架Guice
java轻量级IOC框架Guice
Guice是由Google大牛Bob lee开发的一款绝对轻量级的java IoC容器。其优势在于:
- 速度快,号称比spring快100倍。
- 无外部配置(如需要使用外部可以可以选用Guice的扩展包),完全基于annotation特性,支持重构,代码静态检查。
- 简单,快速,基本没有学习成本。
Guice和spring各有所长,Guice更适合与嵌入式或者高性能但项目简单方案,如OSGI容器,spring更适合大型项目组织。
注入方式
在我们谈到IOC框架,首先我们的话题将是构造,属性以及函数注入方式,Guice的实现只需要在构造函数,字段,或者注入函数上标注@Inject,如:
构造注入
public class OrderServiceImpl implements OrderService {
private ItemService itemService;
private PriceService priceService;
@Inject
public OrderServiceImpl(ItemService itemService, PriceService priceService) {
this.itemService = itemService;
this.priceService = priceService;
}
...
}
属性注入
public class OrderServiceImpl implements OrderService {
private ItemService itemService;
private PriceService priceService;
@Inject
public void init(ItemService itemService, PriceService priceService) {
this.itemService = itemService;
this.priceService = priceService;
}
...
}
函数(setter)注入
public class OrderServiceImpl implements OrderService {
private ItemService itemService;
private PriceService priceService;
@Inject
public void setItemService(ItemService itemService) {
this.itemService = itemService;
}
@Inject
public 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标注注入方法来运行时注入:如
@Provides
public 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));
}
@Override
public void configure() {
final Binder binder = binder();
//TODO: bind interface
binder.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);
}
@Provides
public 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.
轻量级IOC框架Guice的更多相关文章
- java轻量级IOC框架Guice(转)
出处:http://www.cnblogs.com/whitewolf/p/4185908.html Guice是由Google大牛Bob lee开发的一款绝对轻量级的java IoC容器.其优势在于 ...
- java轻量级IOC框架Guice
Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...
- 轻量级IOC框架:Ninject
Ninject 学习杂记 - liucy 时间2014-03-08 00:26:00 博客园-所有随笔区原文 http://www.cnblogs.com/liucy1898/p/3587455.h ...
- 轻量级DI框架Guice使用详解
背景 在日常写一些小工具或者小项目的时候,有依赖管理和依赖注入的需求,但是Spring(Boot)体系作为DI框架过于重量级,于是需要调研一款微型的DI框架.Guice是Google出品的一款轻量级的 ...
- 轻量级IOC框架:Ninject (上)
前言 前段时间看Mvc最佳实践时,认识了一个轻量级的IOC框架:Ninject.通过google搜索发现它是一个开源项目,最新源代码地址是:http://github.com/enkari/ninje ...
- 轻量级IoC框架Ninject.NET搭建
说在之前的话 IOC的概念相信大家比较熟悉了,习惯性称之为依赖注入或控制反转,园子里对基于MVC平台IOC设计模式已经相当多了,但大家都只知道应该怎么应用一个IOC模式,比如Ninject, Unit ...
- 轻量级IOC框架SwiftSuspenders
该框架的1.6版本位于https://github.com/tschneidereit/SwiftSuspenders/blob/the-past/,现在已经出了重新架构的2.0版本,所以我决定先研究 ...
- 轻量级IOC框架:Ninject (下)
一,创建依赖链(Chains of Dependency) 当我们向Ninject请求创建一个类型时,Ninject会去检查该类型和其他类型之间的耦合关系.如果有额外的依赖,Ninject也会解析它们 ...
- IOC框架
一. IOC理论的背景 我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. 图1:软件系统中耦合的对象 如果我们打开机 ...
随机推荐
- POJ2195 Going Home 【最小费用流】+【最佳匹配图二部】
Going Home Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 18169 Accepted: 9268 Descr ...
- ASP.NET Core官方资料入口
ASP.NET 5 has been renamed to ASP.NET Core 1.0 传送门
- 使用Visual Studio 2010写Data Url生成工具C#版本
声明:本文系本人按照真实经历原创.未经许可,谢绝转载. 此文百度经验版本号:怎样用Visual Studio 2010打造Data Url生成工具 源代码下载:用Visual Studio 2010编 ...
- Kafka项目实践
用户日志上报实时统计之编码实践 1.概述 本课程的视频教程地址:<Kafka实战项目之编码实践> 该课程我以用户实时上报日志案例为基础,带着大家去完成各个KPI的编码工作,实现生产模块. ...
- hdu 4965 Fast Matrix Calculation(矩阵高速幂)
题目链接.hdu 4965 Fast Matrix Calculation 题目大意:给定两个矩阵A,B,分别为N*K和K*N. 矩阵C = A*B 矩阵M=CN∗N 将矩阵M中的全部元素取模6,得到 ...
- LeetCode :: Insertion Sort List [具体分析]
Sort a linked list using insertion sort. 仍然是一个很简洁的题目,让我们用插入排序给链表排序:这里说到插入排序.能够来回想一下, 最主要的入门排序算法.就是插入 ...
- 对“demo!demo.Index+HookProc::Invoke”垃圾收集的类型已委托回调。这可能会导致应用程序崩溃、损坏和数据丢失。当传递委托给非托管代码,托管应用程序必须让这些委托保持活着
对"demo!demo.Index+HookProc::Invoke"垃圾收集的类型已委托回调.这可能会导致应用程序崩溃.损坏和数据丢失.当传递委托给非托管代码,托管应用程序必须承 ...
- solaris X86-64下一个ORACLE战斗11.2.0.3.8在一波折叠补丁
solaris X86-64下一个ORACLE战斗11.2.0.3.8补丁: 正确的步骤: 1.BUG6880880 .OPATCH补丁 2.BUG16902043.11.2.0.3.8补丁 情感是练 ...
- don't touch your phone in any unfamiliar way(转)
直到这两天 Chainfire 说,他正尝试在不修改手机 /System 分区的情况下获取 Android 系统 Root 权限,我才想起他在今年 9 月轻描淡写地提到自己已经把 SuperSU 卖给 ...
- Android之Http沟通——4.Android HTTP索取信息:HttpClient
本节介绍: 他谈到了部分HttpURLConnection.本节HttpClient该,Apache为我们提供HttpClient(简单的Http客户端),只是毕竟不是亲儿子.HttpClient在A ...