To demonstrate the following constructor injection that supports multiple parameters, here I write 2 interfaces and their implementation classes. Notes are written in the program notes.
1. Interface (interface)
/* * Creation : 2015年6月30日 */package com.guice.constructorInject;import com.google.inject.ImplementedBy;@ImplementedBy(ServiceImpl.class)publicinterface Service { publicvoidexecute();}
/* * Creation : 2015年6月30日 */package com.guice.constructorInject;import com.google.inject.ImplementedBy;@ImplementedBy(HelloGuiceImpl.class)publicinterface HelloGuice { publicvoidsayHello();}
2. Implementation class (Implementation)
package Com.guice.constructorInject; public class serviceimpl Span class= "Hljs-keyword" >implements service { @Override public void execute () {System.out.println ( "Hello Guice, this is field inject demo! ");}}
package com.guice.constructorInject;import com.google.inject.Singleton;/* * 保证是单例 */@Singletonpublicclass HelloGuiceImpl implements HelloGuice { @Override publicvoidsayHello() { System.out.println("Hello Guice !"); }}
3. Test class
/ * * creation:2015 year June 30 */ PackageCom.guice.constructorInject;ImportCom.google.inject.Guice;ImportCom.google.inject.Inject; Public class constructorinjectdemo { PrivateService service;PrivateHelloguice Helloguice; PublicServiceGetService() {returnService } PublicHelloguiceGethelloguice() {returnHelloguice; }/** * Constructor Injection: Benefits: You can guarantee that there is only one place to complete the attribute injection, * you can ensure that some initialization is done in the constructor: the instantiation of the class is bound to the parameter, limiting the way the class is instantiated. */ /* * @Inject * public Constructorinjectdemo (Service service) {* This.service = service; * } */ / * * Supports multi-parameter constructor injection, but only one constructor must be labeled inject * / @Inject Public Constructorinjectdemo(Service service, Helloguice Helloguice) { This. Service = Service; This. Helloguice = Helloguice; } Public Static void Main(string[] args) {Constructorinjectdemo instance = Guice.createinjector (). getinstance (Constructorinjectdemo.class); Instance.getservice (). Execute (); Instance.gethelloguice (). SayHello (); }}
Output Result:
Hello Guice, this is field inject demo!
Hello Guice!
Guice Learning (ii) constructor injection (Constructor Inject)