Dependency Injection, Di (Dependency injection), its role naturally needless to say, mentioned di containers, such as SPRING,PICOCONTAINER,EJB containers, and so on, recently, Google has created a more lightweight DI container ... Guice!
No more nonsense, first see how guice is to achieve the injection.
Define a simple service interface and its implementation:
Package com.zuidaima.demo.guice;
Public interface MyService ... {
void MyMethod ();
}
Package com.zuidaima.demo.guice;
public class Myserviceimpl implements MyService ... {Public
void MyMethod () ... {
System.out.println ("hello,world!");
}
}
The above is the most common interface and its implementation, there is nothing to say.
Define a test class that includes a reference to a service object that needs to be injected Guice
Package com.zuidaima.demo.guice;
Import Com.google.inject.Inject;
public class Client ... {
MyService service;
@Inject//Tell the container, here's a reference to the service object that needs to be injected into the
void Setservice (MyService service) ... {//Here the method name can be defined arbitrarily
this.service=service;
}
public void MyMethod () ... {
service.mymethod ();
}
}
Here, in addition to adding a @inject, and spring configuration does not make any difference, @Inject, is to say to the container that the service needs to be injected, when the operation, the container will bring an instance to the service, complete the injection process.
Define the Guice module file to tell the container how to inject
Package com.zuidaima.demo.guice;
Import Com.google.inject.Binder;
Import Com.google.inject.Module;
Import Com.google.inject.Scopes;
public class MyModule implements Module ... {Public
void Configure (Binder Binder) ... {Binder.bind (Myservice.class). to (Myserviceimpl.class). in (Scopes.singleton);
This code means that the runtime dynamically assigns the Myserviceimpl object to the object defined by MyService, and that the object is a single instance.
}
}
To create a test class
Package com.zuidaima.demo.guice;
Import Com.google.inject.Guice;
Import Com.google.inject.Injector;
public class Test ... {public
static void Main (string[] args) ... {
mymodule module=new mymodule ()///define injection rule
Injector injector=guice.createinjector (module); According to the injection rule, generate the injector
Client Client=new Client ();
Injector.injectmembers (client)//injection will need to inject the bean, according to the rules, the client to inject
Client.mymethod ();
}
Run test class, console output: hello,world!