Google Guice范例解说之使用入门
时间:2011-03-13
本文通过范例简单地介绍Google Guice的使用,通过下面的范例我们可以知道,Google Guice的使用非常简单。
Google Guice需要使用JDK1.5以上java环境。
下载Google Guice之后,
有以下几个文件:
aopalliance.jar
guice-1.0.jar
guice-servlet-1.0.jar
guice-spring-1.0.jar
guice-struts2-plugin-1.0.jar
本例只使用到guice-1.0.jar文件,将其加入到class path中。
下面简单地介绍范例:
范例1:使用com.google.inject.Module接口实现类
文件名 |
说明 |
HelloGuice.java |
业务逻辑接口定义文件 |
HelloGuiceImpl.java |
业务逻辑接口实现文件 |
HelloGuiceModule.java |
该文件必须实现com.google.inject.Module接口 |
TestGuice.java |
测试文件 |
HelloGuice.java
view plaincopy to clipboardprint?
package com.test.guice;
public interface HelloGuice {
public void sayHello();
}
package com.test.guice;
public interface HelloGuice {
public void sayHello();
}
HelloGuiceImpl.java
view plaincopy to clipboardprint?
package com.test.guice;
public class HelloGuiceImpl implements HelloGuice {
public void sayHello() {
System.out.println("Hello Guice!");
}
}
package com.test.guice;
public class HelloGuiceImpl implements HelloGuice {
public void sayHello() {
System.out.println("Hello Guice!");
}
}
HelloGuiceModule.java
view plaincopy to clipboardprint?
package com.test.guice;
import com.google.inject.Binder;
import com.google.inject.Module;
public class HelloGuiceModule implements Module {
public void configure(Binder binder) {
binder.bind(HelloGuice.class).to(HelloGuiceImpl.class);
}
}
package com.test.guice;
import com.google.inject.Binder;
import com.google.inject.Module;
public class HelloGuiceModule implements Module {
public void configure(Binder binder) {
binder.bind(HelloGuice.class).to(HelloGuiceImpl.class);
}
}
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());
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());
HelloGuice helloGuice = injector.getInstance(HelloGuice.class);
helloGuice.sayHello();
}
}
Google Guice范例解说之使用入门(2)
时间:2011-03-13
运行TestGuice,打印出:
Hello Guice!
范 |