Search code examples
javaguice

asEagerSingleton with factory


I'm very new to Guice, but I have a singleton that I believe would normally be created thusly:

@Provides
@Singleton
private SomeClass getSomeClass()
{
    return someClassFactory(configuration);
}

However, I want this to be eagerly initialized. When I remove the @Singleton annotation and try to bind(SomeClass.class).asEagerSingleton() I get errors:

 1) No implementation for SomeClass was bound.
 2) A binding to SomeClass was already configured

How can I provide an Eagerly initialized singleton that is constructed with parameters or a factory?


Solution

  • The @Provides annotation is a separate way to configure a binding for SomeClass; it's conflicting with the bind(SomeClass.class).asEagerSingleton() binding.

    To fix it, you'll need to write an explicit provider class and bind it using toProvider:

    class MyModule extends AbstractModule {
    
      private static class MyProvider implements Provider<SomeClass> {
        private final OtherStuff otherStuff;
    
        @Inject
        MyProvider(OtherStuff otherStuff) {
          // Inject constructor params if your @Provides method took arguments
          this.otherStuff = otherStuff;
        }
    
        public SomeClass get() {
          return new SomeClass(otherStuff);
        }
      }
    
      protected void configure() {
        bind(SomeClass.class).toProvider(MyProvider.class).asEagerSingleton();
      }
    }