Guice Provider Concrete class binding example
In previous tutorial Guice provider bindings example you saw how to use Google Guice provider interface in interface and it’s implementation model. This tutorial you will see how to get concrete class instance using provider interface:
- Create HelloGuiceConcreteClass.java class:
package com.javahonk.service; /** * Created by Java Honk on 4/20/2015. */ public class HelloGuiceConcreteClass { public String serviceMethod(String msg) { return "Google Guice "+ msg; } }
- HelloGuiceServiceProvider.java:
package com.javahonk.service; import com.google.inject.Provider; /** * Created by Java Honk on 4/20/2015. */ public class HelloGuiceServiceProvider implements Provider<HelloGuiceConcreteClass>{ public HelloGuiceConcreteClass get() { HelloGuiceConcreteClass helloGuiceConcreteClass = new HelloGuiceConcreteClass(); return helloGuiceConcreteClass; } }
- HelloGuiceModule.java which binds concreate class with its provider in singleton scope:
/* * Created by IntelliJ IDEA. * User: Java Honk * Date: 4/9/2015 * Time: 9:26 PM */ package com.javahonk.module; import com.google.inject.AbstractModule; import com.google.inject.Singleton; import com.javahonk.service.HelloGuiceConcreteClass; import com.javahonk.service.HelloGuiceServiceProvider; /** * Created by Java Honk on 4/20/2015. */ public class HelloGuiceModule extends AbstractModule { protected void configure() { bind(HelloGuiceConcreteClass.class).toProvider(HelloGuiceServiceProvider.class).in(Singleton.class); } }
- ProviderConcreteMainClass.java is java main class to test above functionality:
package com.javahonk; import com.google.inject.Guice; import com.google.inject.Injector; import com.javahonk.module.HelloGuiceModule; import com.javahonk.service.HelloGuiceConcreteClass; /** * Created by Java Honk on 4/20/2015. */ public class ProviderConcreteMainClass { public static void main(String[] args) { Injector injector = Guice.createInjector(new HelloGuiceModule()); HelloGuiceConcreteClass helloGuiceConcreteClass = injector.getInstance(HelloGuiceConcreteClass.class); String testStr = helloGuiceConcreteClass.serviceMethod("Provider concrete class implemetation!"); System.out.println(testStr); } }
- Output:
- For more information please visit Google Guice official documentation here
Download project: GoogleGuiceProvider