将@Provides方法绑定为渴望的单例 [英] Binding @Provides method as eager singleton
问题描述
我想使用用@Provides
注释的方法将其绑定为一个渴望的单例.我发现了错误216 ,这表明这不是不可能,但没有明确提及@Provides
注释.
I want to make a binding using a method annotated with @Provides
into an eager singleton. I've found bug 216, which suggests this isn't possible, but doesn't mention the @Provides
annotation explicitly.
我目前有一个类,它本身就是一个单例,它会及时请求eager
个单例,但这不是一个很好的解决方案.
I currently have a class that requests the eager
singletons in time by itself being a singleton, but it's not a very nice solution.
public class LogicModule extends AbstractModule {
@Override public void configure() {
bind(SomeDep.class);
bind(MyWorkaround.class).asEagerSingleton();
}
// cannot add eager requirement here
@Provides @Singleton Logic createLogic(SomeDep dep) {
return LogicCreator.create(dep);
}
private static class MyWorkaround {
@Inject Logic logic;
}
}
我可以在注释附近更改一些使变通方法类过时的东西吗?
Can I change something near the comment that would make the workaround class obsolete?
推荐答案
为什么不使用
bind(Logic.class).toInstance(LogicCreator.create(dep));
//ohh we missing dep
那我们就可以做到
class LogicProvider implements Provider<Logic> {
private final SomeDep dep;
@Inject
public LogicProvider(SomeDep dep) {
this.dep = dep;
}
@Override
public Logic get() {
return LogicCreator.create(dep);
}
}
然后
bind(Logic.class).toProvider(LogicProvider.class).asEagerSingleton();
您甚至可以将SomeDep dep
作为Provider<SomeDep>
传递给您的提供者,然后在LogicCreator.create()
中调用providerDep.get()
,这会更可靠.
You can even pass SomeDep dep
to your provider as Provider<SomeDep>
and then call providerDep.get()
in LogicCreator.create()
that would be a bit more robust.
这篇关于将@Provides方法绑定为渴望的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!