Guice Singleton scope provider example

Guice Singleton scope provider example

In previous Guice tutorial you saw how to use it. In this tutorial I will show you how Singleton scope works in Google Guice framework with simple example:

  • HelloGuiceServiceProvider.java which implements Provider interface:
package com.javahonk.service;

import com.google.inject.Provider;

/**
 * Created by Java Honk on 4/20/2015.
 */
public class HelloGuiceServiceProvider implements Provider<String>{
	
	public String get() {
		System.out.println("HelloGuiceServiceProvider.get() being called");
        return "Singleton scope test";
	}
}
  • HelloGuiceModule.java is module class where binding of String.class has been done with its provider class 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.HelloGuiceServiceProvider;

/**
 * Created by Java Honk on 4/20/2015.
 */
public class HelloGuiceModule extends AbstractModule {

	protected void configure() {
		bind(String.class).toProvider(HelloGuiceServiceProvider.class).in(Singleton.class);

	}
}
  • ProviderConcreteMainClass.java is main class to test Singleton scope:
package com.javahonk;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.javahonk.module.HelloGuiceModule;

/**
 * Created by Java Honk on 4/20/2015.
 */
public class ProviderConcreteMainClass {
	
	public static void main(String[] args) {
        
		Injector injector = Guice.createInjector(new HelloGuiceModule());
		
		// "HelloGuiceServiceProvider.get()" will be called only once
		String value1 = injector.getInstance(String.class); // Called HelloGuiceServiceProvider.get() method
		System.out.println(value1);
		String value2 = injector.getInstance(String.class);  // No call to HelloGuiceServiceProvider.get() method
		System.out.println(value2);
		
		// Another way to get provider instance
		Provider<String> providerInstance = injector.getProvider(String.class);
		System.out.println(providerInstance.get());  // No call to HelloGuiceServiceProvider.get() method
		System.out.println(providerInstance.get());  // No call to HelloGuiceServiceProvider.get() method    
    }    
   
}
  • Output:

2015-04-19_2348

  • For more information please visit Google Guice official documentation here

download  Download project:  GoogleGuiceProvider

Leave a Reply

Your email address will not be published. Required fields are marked *