自己学习Guice的例子[一]

网上已经有很多个Guice的例子了...随便贴贴

定义一个接口:
/**
 * 
 */
package test2;

import com.google.inject.ImplementedBy;

/**
 * @author sun.zhang
 * @Date 2008-4-18
 * @Email [email protected]
 *
 */
//@ImplementedBy(MockService.class)
public interface Service {
	
	public void sayHello();
	
}



接口实现类:
/**
 * 
 */
package test2;

/**
 * @author sun.zhang
 * @Date 2008-4-18
 * @Email [email protected]
 *
 */
public class ServiceImp implements Service{

	public void sayHello() {
		System.out.println("Hello World ...");
	}

}


模块绑定配置类:
/**
 * 
 */
package test2;

import com.google.inject.Binder;
import com.google.inject.Module;

/**
 * @author sun.zhang
 * @Date 2008-4-18
 * @Email [email protected]
 *
 */
public class TestModule implements Module {

	/* (non-Javadoc)
	 * @see com.google.inject.Module#configure(com.google.inject.Binder)
	 */
	public void configure(Binder binder) {
		binder.bind(Service.class).to(ServiceImp.class);
	}

}


客户端类:
/**
 * 
 */
package test2;

import com.google.inject.Inject;

/**
 * @author sun.zhang
 * @Date 2008-4-18
 * @Email [email protected]
 *
 */
public class Client {
	
	private Service service;

	public Client(){}
	
	@Inject									//依赖注入必须的标注
	public Client (Service service){
		System.out.println("This is constructor injector...");
		this.service = service;
	}

//	第二种,set注入方式
//	@Inject
//	public void setClient(Service service){
//		System.out.println("This is set injector...");
//		this.service = service;
//	}
	
	public void sayHello(){
		service.sayHello();
	}
	
}


主函数:
/**
 * 
 */
package test2;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

/**
 * @author sun.zhang
 * @Date 2008-4-18
 * @Email [email protected]
 *
 */
public class GuiceMain {
	
	public static void main(String[] args) {
		
		Service service = new ServiceImp();
//		Service service = new MockService();  // 第二个service的实现
		
		Client client = new Client(service);	//构造器注入
		Module module = new TestModule();
		
		Injector injector = Guice.createInjector(module);//向Guice要注射器
		injector.injectMembers(client);
		client.sayHello();
	}
}



说明:
如果当Client.class中使用两次@inject标签,那么Guice将会自动注入两次。如:

	@Inject									//依赖注入必须的标注
	public Client (Service service){
		System.out.println("This is constructor injector...");
		this.service = service;
	}

	@Inject
	public void setClient(Service service){
		System.out.println("This is set injector...");
		this.service = service;
	}

虽然本意并不是注入两次,只是想提供两个注入方法而已……

你可能感兴趣的:(java,Google,sun,Gmail)