在 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.
是否可以通过多个模块和多个注入(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/