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. Linux中main是如何执行的

    Linux中main是如何执行的 这是一个看似简单的问题,但是要从Linux底层一点点研究问题比较多.找到了一遍研究这个问题的文章,但可能比较老了,还是在x86机器上进行的测试. 原文链接 开始 问题 ...

  2. Python 爬虫:把廖雪峰教程转换成 PDF 电子书

    写爬虫似乎没有比用 Python 更合适了,Python 社区提供的爬虫工具多得让你眼花缭乱,各种拿来就可以直接用的 library 分分钟就可以写出一个爬虫出来,今天尝试写一个爬虫,将廖雪峰老师的 ...

  3. Leetcode题解(六)

    21.Merge Two Sorted Lists 题目 直接上代码: class Solution { public: ListNode *mergeTwoLists(ListNode *l1, L ...

  4. poj 3321Apple Tree

    Apple Tree Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Submit S ...

  5. Problem A

    Problem Description Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum ...

  6. Python基础学习参考(三):内置函数

    一:内置函数 在第一篇文章中,我们简单的认识了一下print()函数和input()函数,也就是输入和输出,这些函数我们可以直接的调用,不要自己定义或者引入什么,对吧?想这样的函数就叫做内置函数.这里 ...

  7. phpmailer 发送邮件(一)

    phpmailer下载地址: PHPMailer : https://github.com/PHPMailer/PHPMailer 一.基本要求 Web访问正常(apache可以正常访问) php 设 ...

  8. 【转】jQuery代码片段备用

    在CSDN看到的,记下备用.原文:http://www.csdn.net/article/2013-07-16/2816238-15-jquery-code-snippets-for-develope ...

  9. SQL Server 初识游标

    ---恢复内容开始--- 游标:游标是一种能从包含多个数据的结果集每次提取一条的机制 游标的特点是: 检索得到的数据集更加灵活 可有针对性的对数据进行操作 拥有对数据进行删除和更新的能力 为何使用游标 ...

  10. Mac安装Elasticsearch时提示:No Java runtime present, requesting install.

    没有安装java的童鞋可以先去安装一下,地址:https://www.java.com/zh_CN/ 安装之后还是提示如下错误: ➜ elasticsearch-2.4.3 bin/elasticse ...