zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    Django各个文件中常见的模块导入
    js模板(template.js)实现页面动态渲染
    Netty 源码 Channel(一)概述
    Netty 源码 NioEventLoop(三)执行流程
    Netty 源码(一)Netty 组件简介
    Netty 源码(二)NioEventLoop 之 Channel 注册
    Java 算法(一)贪心算法
    Netty Reator(三)Reactor 模型
    Netty Reator(二)Scalable IO in Java
    Reactor 模型(一)基本并发编程模型
  • 原文地址:https://www.cnblogs.com/wufengxyz/p/2585388.html
Copyright © 2011-2022 走看看