Gopikrishna K S
Gopikrishna K S

Reputation: 157

Guice bind, toInstance not injecting at startup (eager?) and instead doing during first call (lazy?)

According to this previously answered question (link), toInstance is already an eagerly-loaded singleton but I had an injection of a table dependency which involves the cache update and it is happening only during the first call instead of at service startup. Could someone please tell what I am missing here and how to update the guice injection to make the cache update during startup instead of during the first call?

Upvotes: 1

Views: 1007

Answers (1)

Olivier Grégoire
Olivier Grégoire

Reputation: 35467

Use the PRODUCTION stage to eagerly inject singletons.

Guice's wiki says:

Eager singletons reveal initialization problems sooner, and ensure end-users get a consistent, snappy experience. Lazy singletons enable a faster edit-compile-run development cycle. Use the Stage enum to specify which strategy should be used.

PRODUCTION DEVELOPMENT
.asEagerSingleton() eager eager
.in(Singleton.class) eager lazy
.in(Scopes.SINGLETON) eager lazy
@Singleton *eager lazy

* 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.

So when you create your injector, you should decide whether you want a development stage or a production one. The injection of existing singletons happen at the same time as described above.

To do that, create the Injector like this:

Injector injector = Guice.createInjector(Stage.PRODUCTION, modules);

Upvotes: 1

Related Questions