Guice学习(一)
Guice是Google开发的一个轻量级依赖注入框架(IOC)。Guice非常小而且快,功能类似与Spring,但效率上网上文档显示是它的100倍,而且还提供对Servlet,AOP,Struts等框架的支持;这里是简单代码实现,首先要下载Guice包,http://code.google.com/p/google-guice/这里可以下载;程序结构如下
这里导入了guice包与inject包,最简单的实现;下面是相关代码:
UserDao实现
package com.wf.dao; public class UserDao { public boolean saveUser(){ System.out.println("user have save"); return true; } }
UserService实现
package com.wf.services; import javax.inject.Inject; import com.wf.dao.UserDao; public class UserService { private UserDao userDao; @Inject public void setUser(UserDao userDao) { this.userDao = userDao; } public boolean saveUser(){ boolean result = userDao.saveUser(); System.out.println(result); return result; } }
下面是相当与Spring中xml的一个类MyModule
package com.wf.util; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.wf.services.UserService; public class MyModule implements Module { @Override public void configure(Binder binder) { binder.bind(UserService.class).in(Scopes.SINGLETON); } }
这三个类创建完毕后就可以测试了,下面是单元测试:
package com.wf.test; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.wf.services.UserService; import com.wf.util.MyModule; import junit.framework.TestCase; public class Test extends TestCase { private UserService userService; protected void setUp() throws Exception { userService = new UserService(); } public void testUserService(){ Module module = new MyModule(); Injector in = Guice.createInjector(module); in.injectMembers(userService); assertTrue(userService.saveUser()); } }
以上是注入的简单实现,Guice还有与其它框架的结合使用,可能现在主流还是Spring,不过这个应该也会渐渐被大家注意;感谢Google
http://www.docin.com/p-296920972.html&uid=52823104?bsh_bid=93526465