Search code examples
javadependency-injectionguice

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()


Solution

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