我希望能夠通過輔助注入創建對象的方法的名稱發現/注入已創建的對象。通過輔助注入將創建上下文注入到guice管理的實例中
什麼,我想要做的一個例子:
// what I want guice to create the implementation for this
interface Preferences {
Preference<String> firstName();
Preference<String> lastName();
// other preferences possibly of other types
}
// my interfaces and classes
interface Preference<T> {
T get();
void set(T value);
}
class StringPreference implements Preference<String> {
private final Map<String, Object> backingStore;
private final String key;
@Inject StringPreference(@FactoryMethodName String key,
Map<String, Object> backingStore) {
this.backingStore = backingStore;
this.key = key;
}
public String get() { return backingStore.get(key).toString(); }
public void set(String value) { backingStore.put(key, value); }
}
// usage
public void exampleUsage() {
Injector di = // configure and get the injector (probably somewhere else)
Preferences map = di.createInstance(Preferences.class);
Map<String, Object> backingStore = di.createInstance(...);
assertTrue(backingStore.isEmpty()); // passes
map.firstName().set("Bob");
assertEquals("Bob", map.firstName().get());
assertEquals("Bob", backingStore.get("firstName"));
map.lastName().set("Smith");
assertEquals("Smith", map.lastName().get());
assertEquals("Smith", backingStore.get("lastName"));
}
不幸的是,唯一的辦法,我認爲到目前爲止,實現這是
- 延長輔助注射(通過複製和粘貼)添加我的功能
- 寫一些非常相似的輔助注射,它對我來說
- 寫了很多樣板,這樣做沒有任何幫助
我要找的線沿線的一個解決方案:
- 一些吉斯配置或模式,這是否
- 一些擴展,做的地方,我可以這樣
- 文檔/例子看,這將幫助我自己寫這
- 示例應用程序的替代模式,以完成我想要做的事
感謝這個,其實我最後寫像FactoryModuleBuilder和我自己的類的內部FactoryProvider2,因爲我想減少樣板,因爲我需要可寫屬性。 [見這個要點](https://gist.github.com/4328225) – Matt