guice绑定到实例和asEagersingleton有什么区别

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

当我们做一个

bind(ClassName).toInstance(new ClassName()) 在 configure 方法中,我们本质上是否意味着默认情况下它是 "eagerly initialized singleton"?

如果是,加

有什么用

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

无法追加.asEagerSingleton()

complete signature of toInstance如下:

void toInstance(T instance)

因为 toInstance(T) returns 什么都没有,你不能用 .asEagerSingleton() 链接它。如果这样做,编译将失败。

正如您所怀疑的那样,toInstance 已经是一个急切加载的单例,这就是为什么它是一个链结束方法 (void) 而不是可以进一步限定范围的绑定声明。