Guice - 如何通过多个注射器/模块共享相同的Singleton实例 [英] Guice - How to share the same Singleton instance through multiple injectors/modules

查看:367
本文介绍了Guice - 如何通过多个注射器/模块共享相同的Singleton实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



根据Dhanji的依赖注入一书:


很简单,单身人士的上下文是注射器本身。单身人士的生命与注射器的寿命有关(如图5.8所示)。
因此,每个
注入器只创建一个单例的一个实例。重要的是强调最后一点,因为多个注射器可能存在于同一个应用程序中的
。在
这样的情况下,每个注入器将持有
单例范围对象的不同实例。




是否可以通过多个模块和多个注射器共享相同的Singleton实例?

解决方案

您可以使用注射器.createChildInjector

  // bind shared singletons here 
Injector parent = Guice.createInjector(new MySharedSingletonsModule ());
//创建新的注入器,共享单例
Injector i1 = parent.createChildInjector(new MyModule1(),new MyModule2());
注射器i2 = parent.createChildInjector(新的MyModule3(),新的MyModule4());
//现在注入i1和i2共享父
的所有绑定


In guice, the @Singleton scope does not refer to the Singleton pattern.

According to the "Dependency Injection" book of "Dhanji" :

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.

Is it possible to share the same Singleton instance through multiple modules and multiple injectors ?

解决方案

You can use 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

这篇关于Guice - 如何通过多个注射器/模块共享相同的Singleton实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆