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返回不同的實例嗎?
非常感謝
非常感謝您的回答。這是否意味着我必須將我的密鑰映射到提供者:mapBinder.addBinding(「b」)。toProvider(MyClassBProvider.class);這是否也意味着我必須爲我擁有的每個密鑰創建一個提供者? – Kevin
不,Guice會爲你管理這件事。我已更新我的答案 – eiden
文檔鏈接:[MapBinder文檔](http://google-guice.googlecode.com/git/javadoc/com/google/inject/multibindings/MapBinder.html)(其中列出了'Provider'注入以及)。 –