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

前端 未结 2 639
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    
    0 讨论(0)
  • 2020-12-30 03:04

    I don't see why you need that, but if you really want, it's possible:

    package stackoverflow;
    
    import javax.inject.Inject;
    import javax.inject.Singleton;
    
    import junit.framework.Assert;
    
    import org.junit.Test;
    
    import com.google.inject.AbstractModule;
    import com.google.inject.Guice;
    import com.google.inject.Injector;
    import com.google.inject.Module;
    
    public class InjectorSingletonTest {
    
        static class ModuleOne extends AbstractModule {
            @Override
            protected void configure() {
                bind(MySingleton.class);
            }
        }
    
        static class ModuleTwo extends AbstractModule {
            final MySingleton singleton;
    
            @Inject
            ModuleTwo(MySingleton singleton){
                this.singleton = singleton;
            }
    
            @Override
            protected void configure() {
                bind(MySingleton.class).toInstance(singleton);
            }
        }
    
        @Singleton
        static class MySingleton { }
    
        @Test
        public void test(){
            Injector injectorOne = Guice.createInjector(new ModuleOne());
    
            Module moduleTwo = injectorOne.getInstance(ModuleTwo.class);
            Injector injectorTwo = Guice.createInjector(moduleTwo);
    
            MySingleton singletonFromInjectorOne =
                    injectorOne.getInstance(MySingleton.class);
    
            MySingleton singletonFromInjectorTwo =
                    injectorTwo.getInstance(MySingleton.class);
    
            Assert.assertSame(singletonFromInjectorOne, singletonFromInjectorTwo);
        }
    }
    
    0 讨论(0)
提交回复
热议问题