Search code examples
javabindingguice

When exactly does Google Guice build @Singleton bindings lazily?


From the documentation here:

The only time @Singleton will be lazily initialized (with stage set to PRODUCTION) is below:

  • Guice will only eagerly build singletons for the types it knows about. These are the types mentioned in your modules, plus the transitive dependencies of those types.

I don't think I understand that statement. In my case, all the types are already known at compile time.

I have a Module class (that extends AbstractModule), and it declares a lot of bindings via methods annotated with @Provides @Singleton @Named(...).

And they're all getting created lazily. I want this to happen eagerly (at application startup). What do I need to do here? (I have to use @Singleton annotation for certain reasons)


Solution

  • According to this issue, you cannot do it out of the box using @Provides-style bindings. You can use Provider approach mentioned in the issue:

    public class MyModule extends AbstractModule {
    
      static class MyProvider implements Provider<Foo> {
        @Inject Bar bar;
        @Inject Baz baz;
    
        public Foo get() {
          return Foo.from(bar, baz);
        }
      }
    
      public void configure() {
        bind(Foo.class).toProvider(MyProvider.class).asEagerSingleton();
      }
    }