Guice MapBinding可以返回不同的实例

时间:2013-08-19 08:01:00

标签: java guice

我有一个像这样的Gucie Binding设置:

    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返回不同的实例?

非常感谢

1 个答案:

答案 0 :(得分: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);

        }
    });
}