Guice

Guice is a lightweight dependency injection framework for Java .
即 Guice 是轻量级依赖注入的 Java 框架。

特点

  1. 取消 Bean 概念,使用 Java 代码描述绑定规则
  2. 泛型支持
  3. 专注于 Dependency Injection

依赖

Maven

    <!-- Guice --><dependency><groupId>com.google.inject</groupId><artifactId>guice</artifactId><version>4.2.1</version></dependency><!-- Guice扩展插件:多值绑定 --><dependency><groupId>com.google.inject.extensions</groupId><artifactId>guice-multibindings</artifactId><version>4.2.1</version></dependency>

Gradle

    // Guicecompile 'com.google.inject:guice:4.2.1'// Guice扩展插件:多值绑定compile 'com.google.inject.extensions:guice-multibindings:4.2.1'

注入 @Inject

1.构造器注入(推荐)

public class BookManager {private final BookService bookService;private final PriceService priceService;@Injectpublic BookManager(BookService bookService, PriceService priceService) {this.bookService = bookService;this.priceService = priceService;}...
}

2.设值注入

public class BookManager {@Injectprivate BookService bookService;@Injectprivate PriceService priceService;...
}

绑定 bind(…)

1.类名绑定

    bind(BookService.class).to(BookServiceImpl.class);

2.实例绑定

    bind(BookDao.class).toInstance(new BookDaoImpl()));

3.链式绑定

    bind(PriceService.class).to(PriceServiceImpl.class);bind(PriceServiceImpl.class).toInstance(new PriceServiceImpl() {@Overridepublic BigDecimal getPrice() {return BigDecimal.ONE;}});

4.Provider 绑定

    bind(CurrencyService.class).toProvider(CurrencyProvider.class);@ProvidesList<String> getSupportedCurrencies(CurrencyService currencyService) {return currencyService.getSupportedCurrency();}

5.命名绑定

    @Provides@Named("supportedCurrencies")List<String> getSupportedCurrencies(CurrencyService currencyService) {return currencyService.getSupportedCurrency();}

6.泛型绑定

    bind(new TypeLiteral<List<String>>() {}).annotatedWith(Names.named("supportedCurrencies")).toInstance(Arrays.asList("CNY", "JPY"));

7.集合绑定

    // 集合Set绑定Multibinder<String> currencyBinder = Multibinder.newSetBinder(binder(), String.class);currencyBinder.addBinding().toInstance("ZH");currencyBinder.addBinding().toInstance("EN");currencyBinder.addBinding().toInstance("DE");// 集合Map绑定MapBinder<String, Integer> authorBinder = MapBinder.newMapBinder(binder(),String.class,Integer.class);authorBinder.addBinding("Leif").toInstance(20);authorBinder.addBinding("Chen").toInstance(18);

Module 的相互关系

  1. 并列
  2. 嵌套
  3. 覆盖

作用域

  1. 默认:一般实例,构造速度快
  2. 单例 singleton :构造速度慢的实例,必须线程安全,如数据库连接
  3. Session Scope :含有 session/request 信息的实例

Guice 与 Spring 的依赖注入代码比较

一、Spring 依赖注入

  • Dao
public interface UserDao {void save();
}
public class UserDaoImpl implements UserDao {@Overridepublic void save() {System.out.println("Spring BookDao method: save().");}
}
  • Service
public interface UserService {void save();
}
public class UserServiceImpl implements UserService {private final UserDao userDao;public UserServiceImpl(UserDao userDao) {this.userDao = userDao;}@Overridepublic void save() {System.out.println("Spring BookService method: save().");userDao.save();}
}
  • Manager
public class UserManager {private final UserService userService;public UserManager(UserService userService) {this.userService = userService;}public void test() {userService.save();}
}
  • 配置文件 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="userDao" class="com.chen.spring.dao.impl.UserDaoImpl"/><bean id="userService" class="com.chen.spring.service.impl.UserServiceImpl"><constructor-arg ref="userDao"/></bean><bean id="userManager" class="com.chen.spring.manager.UserManager"><constructor-arg ref="userService"/></bean></beans>
  • 主程序
public class SpringApp {public static void main(String[] args) {BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");UserManager userManager = (UserManager) beanFactory.getBean("userManager");userManager.test();}
}

二、Guice 依赖注入

  • Dao
public interface BookDao {void save();
}
public class BookDaoImpl implements BookDao {@Overridepublic void save() {System.out.println("Guice BookDao method: save().");}
}
  • Service
public interface BookService {void save();
}
public class BookServiceImpl implements BookService {private final BookDao bookDao;@Injectpublic BookServiceImpl(BookDao bookDao) {this.bookDao = bookDao;}@Overridepublic void save() {System.out.println("Guice BookService method: save().");bookDao.save();}
}
  • Manager
public class BookManager {private final BookService bookService;@Injectpublic BookManager(BookService bookService) {this.bookService = bookService;}public void test() {bookService.save();}
}
  • Module
public class BookModule extends AbstractModule {@Overrideprotected void configure() {bind(BookDao.class).toInstance(new BookDaoImpl());bind(BookService.class).to(BookServiceImpl.class);}
}
  • 主程序
public class GuiceApp {public static void main(String[] args) {Guice.createInjector(new BookModule()).getInstance(BookManager.class).test();}
}

参考

[1] 慕课网:使用Google Guice实现依赖注入
[2] 代码

Google Guice相关推荐

  1. guice google_与Google Guice的动手实践

    guice google by Sankalp Bhatia 通过Sankalp Bhatia 与Google Guice的动手实践 (A hands-on session with Google G ...

  2. Google Guice使用入门

    2019独角兽企业重金招聘Python工程师标准>>> 本文通过范例简单地介绍Google Guice的使用,通过下面的范例我们可以知道,Google Guice的使用非常简单. G ...

  3. Google Guice范例解说之使用入门

    http://www.cnblogs.com/xd502djj/archive/2012/06/25/2561414.html Google Guice范例解说之使用入门 http://code.go ...

  4. 超轻量级DI容器框架Google Guice与Spring框架的区别教程详解及其demo代码片段分享...

    超轻量级DI容器框架Google Guice与Spring框架的区别教程详解及其demo代码片段分享 DI框架 Google-Guice入门介绍 转载于:https://www.cnblogs.com ...

  5. guice 实例_使用Google Guice消除实例之间的歧义

    guice 实例 如果接口有多个实现,则Google guice提供了一种精巧的方法来选择目标实现. 我的示例基于Josh Long ( @starbuxman )的出色文章,内容涉及Spring提供 ...

  6. guice 框架_玩! 框架+ Google Guice

    guice 框架 在我目前正在工作的项目中,我们开始使用Google Guice. 对于那些不知道的人, Google Guice是一个依赖项注入框架. 依赖项注入的基本思想是提供一个其依赖的类,而不 ...

  7. 使用Google Guice消除实例之间的歧义

    如果接口有多个实现,则Google guice提供了一种精巧的方法来选择目标实现. 我的示例基于Josh Long ( @starbuxman )的出色文章,内容涉及Spring提供的类似机制. 因此 ...

  8. 玩! 框架+ Google Guice

    在我目前正在工作的项目中,我们开始使用Google Guice. 对于那些不知道的人, Google Guice是一个依赖项注入框架. 依赖项注入背后的基本思想是提供一个它依赖的类,而不是使依赖类负责 ...

  9. Google Guice 一个轻量级的依赖注入框架

    1.美图 2.概述 2.1 背景 在做项目的时候,看见有段代码直接是使用Google Guice 注入了avaitor表达式. 2.1 官网 Github 主页:https://github.com/ ...

  10. Google Guice使用入门(转)

    本文通过范例简单地介绍Google Guice的使用,通过下面的范例我们可以知道,Google Guice的使用非常简单. Google Guice需要使用JDK1.5以上java环境. 下载Goog ...

最新文章

  1. 鼠标按键获取感兴趣区域 2
  2. Timer TimeTask Handler
  3. @retention注解作用_分分钟带你玩转SpringBoot自定义注解
  4. cannot find any entry in order attachment link
  5. python课程笔记_Python课程笔记(一)
  6. linux更新命令centos,CentOS 7.0命令更新新版特性
  7. vc升级失败恢复快照后数据不一致问题
  8. “钉钉打卡神器”开发者被判五年半!
  9. linux内核驱动工作队列用法
  10. echarts常用术语
  11. 【Gym-101908 B】Marbles【SG函数】
  12. shell批量修改后缀_用shell脚本批量修改文件后缀名
  13. MySQL中临时表(TEMPORARY)
  14. GCC、GNU到底啥意思?
  15. App在后台被杀死后重启-重进首页方法
  16. 初学Python案例之一(开平方代码)
  17. 索引服务器(全文索引)的使用
  18. office2010 word 关闭很慢
  19. 离线安装ruby、rubygems
  20. 【论文笔记】VOLO: Vision Outlooker for Visual Recognition

热门文章

  1. 渗透测试-地基篇-拖库七种方法(十一)
  2. 最新款电影程序源码 影院网站源码 在线采集多资源播放器去广告
  3. Java 苹果支付applepay服务端验证
  4. Apple Pay发展与安全
  5. linux 远程 mox,MOX 文件扩展名: 它是什么以及如何打开它?
  6. 利用canvas制作乱跑的小球
  7. docker安装镜像
  8. bom 根据一阶 BOM 表整理多阶层 BOM 表
  9. 文明4 java_文明4主题曲《Baba Yetu》(敬请关注中文歌词部分~)
  10. s深度linux没有ll等命令的解决办法