1
import com.google.inject.Injector;
import static com.google.inject.Guice.createInjector;

public final class BatchFactory {

      private static class Holder {
          private static final Injector INJECTOR = createInjector(new BatchModule());
          private static final batchProvider PROVIDER_INSTANCE = INJECTOR
                  .getInstance(BatchProvider.class);
      }

      public static BatchProvider getProviderInstance() {
          return Holder.PROVIDER_INSTANCE;
      }
  }

public class BatchModule extends AbstractModule {
      @Override
      protected void configure() {
          bind(BatchProvider.class).to(
                  BatchProviderImpl.class);
      }
  }

BatchProvider is the Interface and BatchProviderImpl is the class implementation.

Here I am using a class BatchFactory to create the @Singleton instance of BatchProviderImpl class.

Can I use @Singleton annotation of google guice to make BatchFactory class @Singleton

saurabh agarwal
  • 2,124
  • 4
  • 24
  • 46
  • Possible duplicate of [Guice: differences between Singleton.class and @Singleton](https://stackoverflow.com/questions/14781471/guice-differences-between-singleton-class-and-singleton) – tkruse Jan 10 '18 at 00:31

1 Answers1

3

See the duplicate question, you can do

bind(Service.class).to(ServiceImpl.class).in(Singleton.class);

Or:

@Provides @Singleton
public ServiceImpl providesService() {
    return new ServiceImpl();
}
tkruse
  • 10,222
  • 7
  • 53
  • 80