簡體   English   中英

Guice MapBinding可以返回不同的實例

[英]Can Guice MapBinding Returns Distinct Instance

我有一個像這樣的Gucie綁定設置:

    MapBinder<String, MyInterface> mapBinder = MapBinder.newMapBinder(binder(), String.class, MyInterface.class);
    mapBinder.addBinding("a").to(MyClassA.class);
    mapBinder.addBinding("b").to(MyClassB.class);

MyClassA當然實現了MyInterface。

每當我用鍵查詢注入的映射時,它總是返回相同的實例:

class UserClass {
    private final Map<String, MyInterface> map;
    public UserClass(Map<String, MyInterface> map) {
        this.map = map;
    }

    public void MyMethod() {
        MyInterface instance1 = map.get("a");
        MyInterface instance2 = map.get("a");
        .....
    }

     ......
}

這里我得到的instance1和instance2總是相同的對象。 有沒有辦法配置Gucie總是從MapBinder返回不同的實例?

非常感謝

您可以通過注入Map<String, Provider<MyInterface>>而不是Map<String, MyInterface>來實現此Map<String, MyInterface>

interface MyInterface {}

class MyClassA implements MyInterface {}
class MyClassB implements MyInterface {}

class UserClass {
    @Inject private Map<String, Provider<MyInterface>> map;

    public void MyMethod() {
        Provider<MyInterface> instance1 = map.get("a");
        Provider<MyInterface> instance2 = map.get("a");
    }
}

@Test
public void test() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            MapBinder<String, MyInterface> mapBinder = MapBinder.newMapBinder(binder(), String.class, MyInterface.class);
            mapBinder.addBinding("a").to(MyClassA.class);
            mapBinder.addBinding("b").to(MyClassB.class);

        }
    });
}

暫無
暫無

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

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