Google Guice 小试牛刀
Google Guice是一个轻量级Dependency Injection依赖注入框架,能够提供动态注入,即当不知道注射的这个对象注射给谁呢,需要在运行时才能得到的的这个接口的实现,这是Spring DI所不具有的,Spring DI所有配置都是写死的,并且Spring DI在应用程序启动时所有依赖注入关系都会初始好,而Google Guice则可以根据需要进行依赖注入初始化,也就是说只有当需要时,就可以对依赖注入关系进行初始化。
?
引入Google Guice包,从这个网址可以下载http://google-guice.googlecode.com/files/guice-3.0.zip
?
一。CommentDao.java
?
package com.template.guice;import com.google.inject.Guice;import com.google.inject.Injector;/** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 11-8-2 * Time: 下午9:55 */public class Main { public static void main(String[] args) { Injector injector = Guice.createInjector(new CommentModule()); CommentService commentService = injector.getInstance(CommentServiceImpl.class); commentService.comment(); }}?
@Inject表示Guice会隐式调用CommentServiceImpl的构造方法,而CommentModule则表示需要将CommentDao以CommentDaoImpl来注入对象中。
1 楼 bastengao 2011-08-03 支持一下,我也很喜欢guice.一直想在产品中使用,想让guice与spring mvc整合,不知道楼主有什么解决方法? 2 楼 Wind_ZhongGang 2011-08-03 呵呵,我也是刚开始关注这个东西,至于你说的整合,我想还得继续深入研究下才能找到解决方法。不过感兴趣的话,咱们好友聊,共同进步嘛,哈哈。 3 楼 Wind_ZhongGang 2011-08-03 发现了,Google Guice提供了一个guice-spring-3.0.jar,使用这个包可以把我们的Spring配置转换成Google Guice 4 楼 cantellow 2011-08-03 听说guice性能很好,楼主有木有这方面的资料 5 楼 Wind_ZhongGang 2011-08-03 可以直接去http://code.google.com/p/google-guice/这个上面看,不过是英文的 6 楼 bastengao 2011-08-03 Wind_ZhongGang 写道发现了,Google Guice提供了一个guice-spring-3.0.jar,使用这个包可以把我们的Spring配置转换成Google Guice嗯,我也找到了,guice 提供的spring 插件可以将spring的bean注入到guice中。但我的目的可否将Guice的bean注入到了spring mvc中的Controller?