1

I have a Gucie Binding setup like this:

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

MyClassA implements MyInterface of course.

Everytime I get query the injected map with a key, it always returns me the same instance:

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

     ......
}

Here instance1 and instance2 I got are always the same object. Is there any way to configure Gucie to always returns different instances from MapBinder?

Many thanks

4

1 回答 1

3

您可以通过注入Map<String, Provider<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);

        }
    });
}
于 2013-08-19T08:43:21.500 回答