google guice 入门学习笔记(一)
package com.bcw.test;import com.google.inject.ImplementedBy;@ImplementedBy(HelloGuiceImpl.class)public interface HelloGuice { public void sayHello();}?
package com.bcw.test;public class HelloGuiceImpl implements HelloGuice {@Overridepublic void sayHello() {System.out.println("hello");}}?
下面是需要调用这个接口的3类,分别采用构造器,set方法,和字段注入:
package com.bcw.test;import com.google.inject.Inject;public class Client {private final HelloGuice hello;//构造函数方式注入@Injectpublic Client(HelloGuice hello) {this.hello = hello;}public HelloGuice getHello() {return hello;}}?
package com.bcw.test;import com.google.inject.Inject;public class Client2 {private HelloGuice hello;public HelloGuice getHello() {return hello;}// set方法注入@Injectpublic void setHello(HelloGuice hello) {this.hello = hello;}}?
package com.bcw.test;import com.google.inject.Inject;public class Client3 {// 字段注入@Inject private HelloGuice hello;public HelloGuice getHello() {return hello;}}?
以下是测试用例:
package com.bcw.test;import junit.framework.TestCase;import com.google.inject.Guice;import com.google.inject.Injector;public class TestHelloGuice extends TestCase {public void testSayHello() {Injector injector = Guice.createInjector();HelloGuice helloGuice = injector.getInstance(HelloGuice.class);helloGuice.sayHello();// 构造器注入Client c = injector.getInstance(Client.class);c.getHello().sayHello();// set方法注入Client2 c2 = injector.getInstance(Client2.class);c2.getHello().sayHello();// 字段注入Client3 c3 = injector.getInstance(Client3.class);c3.getHello().sayHello();}}?
console打印输出:
hellohellohellohello
?
推荐使用构造器注入方式.
?
1 楼 readythink 2009-05-21 谢谢楼主.正准备看看guice. 2 楼 sogo1986 2009-05-21 顶。guice和spring都是不错的IOC容器 3 楼 kjj 2009-05-21 那个implementBy()好像有点繁琐,难道以后要一个一个的找出来些进去! 4 楼 bcw104 2009-05-22 kjj 写道那个implementBy()好像有点繁琐,难道以后要一个一个的找出来些进去!