Tania
Tania

Reputation: 1925

What's the difference between guice bind to instance and asEagersingleton

When we do a

bind(ClassName).toInstance(new ClassName()) inside the configure method do we essentially mean that it is an "eagerly initialized singleton" by default?

If yes, what is the use of adding

bind(ClassName).toInstance(new ClassName()).asEagerSingleton()

Upvotes: 0

Views: 1574

Answers (1)

Olivier Grégoire
Olivier Grégoire

Reputation: 35477

It's not possible to append .asEagerSingleton()

The complete signature of toInstance is the following:

void toInstance(T instance)

Since toInstance(T) returns nothing, you can't chain it with .asEagerSingleton(). The compilation will fail if you do that.

As you suspected, toInstance is already an eagerly-loaded singleton, this is why it's a chain-ending method (void) and not a binding declaration that can be further scoped.

Upvotes: 2

Related Questions