This article simply introduces the use of Google Guice by example, and we can see from the example below that the use of Google Guice is very simple.
Google Guice needs to use the Java environment above JDK1.5.
After downloading Google Guice,
There are several documents:
Aopalliance.jar
Guice-1.0.jar
Guice-servlet-1.0.jar
Guice-spring-1.0.jar
Guice-struts2-plugin-1.0.jar
This example uses only the Guice-1.0.jar file to add it to the class path.
Here is a brief example:
Example 1: Implementing a class using the Com.google.inject.Module interface
Filename |
Description |
Helloguice.java |
Business logic Interface Definition file |
Helloguiceimpl.java |
Business logic Interface Implementation file |
Helloguicemodule.java |
The file must implement the Com.google.inject.Module interface |
Testguice.java |
Test files |
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 ();
}
}