我对Guice很新,但我有一个我认为通常会创造的单身人士:
@Provides
@Singleton
private SomeClass getSomeClass()
{
return someClassFactory(configuration);
}
但是,我希望这是急切的初始化。当我删除@Singleton
注释并尝试bind(SomeClass.class).asEagerSingleton()
时,我会收到错误:
1) No implementation for SomeClass was bound.
2) A binding to SomeClass was already configured
如何提供由参数或工厂构建的Eagerly初始化单例?
答案 0 :(得分:2)
@Provides
注释是为SomeClass
配置绑定的单独方式;它与bind(SomeClass.class).asEagerSingleton()
绑定冲突。
要修复它,您需要编写一个显式的提供程序类并使用toProvider
绑定它:
class MyModule extends AbstractModule {
private static class MyProvider implements Provider<SomeClass> {
private final OtherStuff otherStuff;
@Inject
MyProvider(OtherStuff otherStuff) {
// Inject constructor params if your @Provides method took arguments
this.otherStuff = otherStuff;
}
public SomeClass get() {
return new SomeClass(otherStuff);
}
}
protected void configure() {
bind(SomeClass.class).toProvider(MyProvider.class).asEagerSingleton();
}
}