例2:使用Java Annotation
我们也可以直接为HelloGuice加上@ImplementedBy注释,而省略掉对com.google.inject.Module的实现。
HelloGuice.java
view plaincopy to clipboardprint?
package com.test.guice;
import com.google.inject.ImplementedBy;
@ImplementedBy(HelloGuiceImpl.class)
public interface HelloGuice {
public void sayHello();
}
package com.test.guice;
import com.google.inject.ImplementedBy;
@ImplementedBy(HelloGuiceImpl.class)
public interface HelloGuice {
public void sayHello();
}
TestGuice.java
view plaincopy to clipboardprint?
package com.test.guice;
import junit.framework.TestCase;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class TestGuice extends TestCase {
public void testHelloGuice() {
//Injector injector = Guice.createInjector(new HelloGuiceModule());
Injector injector = Guice.createInjector();
HelloGuice helloGuice = injector.getInstance(HelloGuice.class);
helloGuice.sayHello();
}
}
package com.test.guice;
import junit.framework.TestCase;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class TestGuice extends TestCase {
public void testHelloGuice() {
//Injector injector = Guice.createInjector(new HelloGuiceModule());
Injector injector = Guice.createInjector();
HelloGuice helloGuice = injector.getInstance(HelloGuice.class);
helloGuice.sayHello();
}
}
HelloGuiceModule.java不再需要。其余的文件内容不变。
运行TestGuice,打印出:
Hello Guice!
本文通过范例简单地介绍了Google Guice的使用。至于Google Guice与Spring,Struts等的集成,本文未加涉及,请参考其他文章。 |