asEagerSingleton与工厂

时间:2018-05-08 12:24:39

标签: java guice

我对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初始化单例?

1 个答案:

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