我希望能够通过辅助注入到创建的对象中发现/注入创建对象的方法的名称。
我想做的一个例子:
// 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"));
}
不幸的是,到目前为止,我想到的唯一方法是
- 扩展辅助注入(通过复制和粘贴)以添加我的功能
- 写一些非常类似于为我做的辅助注射的东西
- 编写很多样板文件,在没有 guices 帮助的情况下做到这一点
我正在寻找以下方面的解决方案:
- 执行此操作的一些 guice 配置或模式
- 一些这样做的扩展
- 我可以查看的文档/示例将帮助我自己编写此内容
- 示例应用程序的替代模式来完成我想做的事情