2013-08-19 28 views
1

我有一個Gucie綁定的設置是這樣的:燦吉斯MapBinding返回不同實例

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

非常感謝

回答

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); 

     } 
    }); 
} 
+0

非常感謝您的回答。這是否意味着我必須將我的密鑰映射到提供者:mapBinder.addBinding(「b」)。toProvider(MyClassBProvider.class);這是否也意味着我必須爲我擁有的每個密鑰創建一個提供者? – Kevin

+0

不,Guice會爲你管理這件事。我已更新我的答案 – eiden

+1

文檔鏈接:[MapBinder文檔](http://google-guice.googlecode.com/git/javadoc/com/google/inject/multibindings/MapBinder.html)(其中列出了'Provider '注入以及)。 –