asEagerSingleton 与工厂
asEagerSingleton with factory
我是 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 初始化单例?
@Provides
注释是为 SomeClass
配置绑定的单独方法;它与 bind(SomeClass.class).asEagerSingleton()
绑定冲突。
要修复它,您需要编写一个显式提供程序 class 并使用 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();
}
}
我是 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 初始化单例?
@Provides
注释是为 SomeClass
配置绑定的单独方法;它与 bind(SomeClass.class).asEagerSingleton()
绑定冲突。
要修复它,您需要编写一个显式提供程序 class 并使用 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();
}
}