From the documentation here:
The only time @Singleton will be lazily initialized (with stage set to PRODUCTION) is below:
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)
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();
}
}