Java Guice MapBinding能否返回不同的实例

Java Guice MapBinding能否返回不同的实例,java,guice,Java,Guice,我有一个Gucie绑定设置,如下所示: MapBinder<String, MyInterface> mapBinder = MapBinder.newMapBinder(binder(), String.class, MyInterface.class); mapBinder.addBinding("a").to(MyClassA.class); mapBinder.addBinding("b").to(MyClassB.class); MapBinder

我有一个Gucie绑定设置,如下所示:

    MapBinder<String, MyInterface> mapBinder = MapBinder.newMapBinder(binder(), String.class, MyInterface.class);
    mapBinder.addBinding("a").to(MyClassA.class);
    mapBinder.addBinding("b").to(MyClassB.class);
MapBinder-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");
        .....
    }

     ......
}
class用户类{
私人最终地图;
公共用户类(映射){
this.map=map;
}
公共方法(){
MyInterface instance1=map.get(“a”);
MyInterface instance2=map.get(“a”);
.....
}
......
}
这里我得到的instance1和instance2总是同一个对象。有没有办法将Gucie配置为始终从MapBinder返回不同的实例


非常感谢

您可以通过注入
Map
而不是
Map
来实现这一点

接口MyInterface{}
类MyClassA实现MyInterface{}
类MyClassB实现MyInterface{}
类用户类{
@注入私有地图;
公共方法(){
Provider instance1=map.get(“a”);
Provider instance2=map.get(“a”);
}
}
@试验
public void test()引发异常{
Injector=Guice.createInjector(新抽象模块(){
@凌驾
受保护的void configure(){
MapBinder MapBinder=MapBinder.newMapBinder(binder(),String.class,MyInterface.class);
mapBinder.addBinding(“a”).to(MyClassA.class);
mapBinder.addBinding(“b”).to(MyClassB.class);
}
});
}

非常感谢您的回答。这是否意味着我必须将我的密钥映射到提供者:mapBinder.addBinding(“b”).toProvider(MyClassBProvider.class);这是否也意味着我必须为我拥有的每个密钥创建一个提供者?Doc link:(它还列出了
provider
injection)。
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);

        }
    });
}