1

我的代码看起来像 ff.:

Interface i;
if (someCondition) {
  ImplementationA a = new ImplementationA();
  a.setFieldA(someValueA);
  a.setFieldB(someValueB);
  i = a;
} else {
  ImplementationB b = new ImplementationB();
  b.setFieldC(someValueC);
  i = b;
}
// Do something with i.

我的问题是:

  1. 我应该在这里使用依赖注入还是超出了该技术的范围?
  2. 如果我应该在这里使用依赖注入,我如何使用 Google Guice 来完成它?
4

1 回答 1

1

动态运行时注入超出范围。您必须通过模块配置要使用的实现。您仍然可以使用工厂(查看多重绑定和辅助注入)并为自己节省设置实例的工作......

于 2012-07-19T17:49:17.203 回答