Guice - How to share the same Singleton instance through multiple injectors/modules

前端 未结 2 645
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 02:02

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

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

Very si

2条回答
  •  孤城傲影
    2020-12-30 02:54

    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
    

提交回复
热议问题