java - Guice - 如何通过多个注入(inject)器/模块共享同一个单例实例

标签 java dependency-injection singleton guice

在 guice 中,@Singleton 范围不引用 Singleton 模式。

根据《Dhanji》的《Dependency Injection》一书:

Very simply, a singleton’s context is the injector itself. The life of a singleton is tied to the life of the injector (as in figure 5.8). Therefore, only one instance of a singleton is ever created per injector. It is important to emphasize this last point, since it is possible for multiple injectors to exist in the same application. In such a scenario, each injector will hold a different instance of the singleton-scoped object.

Singleton scope

是否可以通过多个模块和多个注入(inject)器共享同一个单例实例?

最佳答案

您可以使用 Injector.createChildInjector :

// bind shared singletons here
Injector parent = Guice.createInjector(new MySharedSingletonsModule());
// create new injectors that share singletons
Injector i1 = parent.createChildInjector(new MyModule1(), new MyModule2());
Injector i2 = parent.createChildInjector(new MyModule3(), new MyModule4());
// now injectors i1 and i2 share all the bindings of parent

关于java - Guice - 如何通过多个注入(inject)器/模块共享同一个单例实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8356640/

相关文章:

java.lang.运行时异常 "Cannot run program"

java - 初始化二维字符数组以测试打印时出错

rust - 尝试在 Rust 中进行控制反转时未实现 `Send`

ios - 从单例中获取触摸坐标

objective-c - 如何在类方法中访问 Objective-C 属性

java - LWJGL 矩阵堆栈意外行为

java - 提取字符串中的字符串

java - 不太了解Struts2 XWork中依赖注入(inject)的机制

asp.net-mvc - 在Controller中使用依赖注入(inject)和存储库模式时如何处理业务规则?

c++ - Meyers 的单例实现实际上是如何实现单例的