Guice 使用单例范围辅助注入
我有一个接口 A,一个类 B 实现 A。
但是,B 的构造函数如下所示:
public class B (C c){}
其中 C 是第三方库类,只能在引导程序后创建。 我希望 B 成为单身人士。
我发现在 Guice 中实现这一点很困难。我知道我可以使用辅助注入器来执行此操作:
public class B (@Assisted C c){}
public AFactory {
public A createA(C c);
}
但看起来辅助注入器无法生成单例实例。
知道如何实现吗?
谢谢。
I have an interface A, and a class B implement A.
However, the constructor of B is looks like:
public class B (C c){}
where C is a thrid party library class and can only be created on after the bootstrap.
and I want to B to be a singleton.
I found it difficult to implement this in Guice. I know I can use assisted injector to do this:
public class B (@Assisted C c){}
public AFactory {
public A createA(C c);
}
but it looks assisted injector canot produce a singleton instance.
any idea how to implement this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您所发现的,您不能使用辅助注入来创建单例。辅助注入适用于需要编程参数且单例不是以编程方式创建的实例。
单例是惰性构造的,除非您在模块中的绑定上调用
asEagerSingleton()
。因此,您可以简单地将 C 注入 B,并且您的 C 实例将在创建 guice 注入器后创建。如果 C 的创建更复杂,请创建 C 的提供者并将其绑定到您的模块中。As you found out, you cannot use assisted inject to create singletons. Assisted inject is for instances that require programmatic parameters and singletons are not created programatically.
Singletons are constructed lazily unless you invoke
asEagerSingleton()
on the binding in your module. So you can simply inject C into B and your instance of C will be created after the guice injector has been created. If the creation of C is more involved, create a provider of C and bind it in your module.在您的
Module
中,您可以创建一个C
实例并将其添加到上下文中。然后你就可以正常注释类B
了。In your
Module
you could create an instance ofC
and add it to the context. Then you could annotate classB
normally.我认为您不需要在这里进行辅助注射。
您是否考虑过实现(和绑定)
Provider
?然后,C
就可以注入到B
中(以及任何需要C
的地方)。I don't think you need Assisted injection here.
Did you think about implementing (and binding) a
Provider<C>
? ThenC
becomes injectable intoB
(and anywhere aC
is needed).