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

在 guice 中,@Singleton范围不是指单例模式。

根据“Dhanji”的“依赖注入”一书:

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

Singleton scope

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


答案 1

您可以使用 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

答案 2

我不明白你为什么需要它,但如果你真的想要,这是可能的:

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);
    }
}

推荐