java - Guice MapBinding 能否返回不同的实例

标签 java guice

我有一个像这样的 Gucie 绑定(bind)设置:

    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。

每次我用一个键查询注入(inject)的映射时,它总是返回相同的实例:

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

非常感谢

最佳答案

您可以通过注入(inject) 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);

        }
    });
}

关于java - Guice MapBinding 能否返回不同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308981/

相关文章:

java - 从 ArrayList<MyObject> 获取 Set<String>

javax.mail.internet.InternetAddress RFC 822 验证

java - Hibernate 4 connection.autocommit=false 忽略

java - 云端点 : Access Paramters in Servlet Filter

java - 在Java中注入(inject)多个参数同一个接口(interface)

java - 单击 ListView 上的按钮会显示相同的输出

java - 如何在 RichFaces 中选择所有同类元素

java - 使用 Guice 设置属性的正确方法是什么?

java - 注入(inject)实例上的 Guice 空指针异常

java - 从对象创建对象输出流