gpt4 book ai didi

java - asEagerSingleton 与工厂

转载 作者:行者123 更新时间:2023-12-02 02:09:26 25 4
gpt4 key购买 nike

我对 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

如何提供使用参数或工厂构造的热切初始化单例?

最佳答案

@Provides 注释是为 SomeClass 配置绑定(bind)的单独方法;它与 bind(SomeClass.class).asEagerSingleton() 绑定(bind)冲突。

要修复此问题,您需要编写一个显式提供程序类并使用 toProvider 绑定(bind)它:

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

关于java - asEagerSingleton 与工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50233581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com