【发布时间】:2012-01-12 20:02:48
【问题描述】:
我有一个使用 GIN 在入口点注入依赖项的 web 应用程序。
private InjectorService injector = GWT.create(InjectorService.class);
@GinModules({PlaceContollerInject.class, RootViewInject.class})
public interface InjectorService extends Ginjector {
RootView getRootView();
PlaceController getPlaceConroller();
}
public class RootViewInject extends AbstractGinModule {
@Override
protected void configure() {
bind(RootView.class).to(RootViewImpl.class);
}
}
我需要一个使用不同 RootView 实现的移动版本。依赖关系在以下模块中描述
public class RootViewMobileInject extends AbstractGinModule {
@Override
protected void configure() {
bind(RootView.class).to(RootViewMobileImpl.class);
}
}
问题是如何有条件地选择需要的依赖项,无论我们需要移动版本还是默认版本。 我见过GWT-GIN Multiple Implementations,但还没有想出那个解决方案,因为提供者打破了依赖关系链,而工厂模式打破了可测试性。 在“Big Modular Java with Guice”视频中here (12 minute) Guice 的模块注入器被介绍为工厂的替代品。所以我的问题是我应该为我的应用程序的移动版本和默认版本(如 MobileFactory 和 DefaultFactory)创建不同的 Ginjector,否则这是不好的做法,我应该为一个 Ginjector 实例配置所有需要的版本。例如像这样的注解绑定。
public class RootViewMobileInject extends AbstractGinModule {
@Override
protected void configure() {
bind(RootView.class).annotatedWith(Mobile.class).to(RootViewMobileImpl.class);
}
}
并在 GWT 入口点使用 @Mobile 注释绑定
@Inject
private void setMobileRootView(@Mobile RootView rw) {
this.rw = rw;
}
在上面这样一个简化的例子中,它可能是可能的。但是,如果应用程序有更多依赖项,需要移动版本和默认版本。它看起来像是回到了无法测试的“丑陋”(正如 Guice 的演讲中所说的)工厂。 对不起我的英语不好。任何帮助表示赞赏。
【问题讨论】:
-
我只是想补充一点,这里的想法和来自@aldanok 的解决方案也可以用于应用程序中的客户特定定制。客户端特定:gwt.xml + gin 模块 + 接口实现。