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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM