簡體   English   中英

Guice - 如何通過多個噴射器/模塊共享同一個Singleton實例

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

在guice中,@ Singleton范圍不涉及Singleton模式。

根據“Dhanji”的“依賴注入”一書:

很簡單,單例的上下文就是注入器本身。 單身的壽命與注射器的壽命有關(如圖5.8所示)。 因此,每個注射器只創建一個單例實例。 重要的是要強調最后一點,因為多個噴射器可能存在於同一應用中。 在這種情況下,每個注入器將保存單例范圍對象的不同實例。

單身范圍

是否可以通過多個模塊和多個噴射器共享同一個Singleton實例?

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

我不明白為什么你需要那個,但如果你真的想要,那就有可能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM