【发布时间】:2012-04-01 10:34:36
【问题描述】:
假设您有一个在其核心项目中使用 Guice 绑定的 PlayN 游戏:
/* PlayN core Guice module */
public class MyGameModule extends AbstractModule {
@Override
protected void configure() {
bindConstant().annotatedWith(Title.class).to("My game title");
// Other bindings...
}
}
如果您想在游戏的 GWT 项目(使用 Gin)上使用那些相同的绑定,该怎么办?
在 Java 项目中非常简单:
/* PlayN Java Guice module */
public class MyGameModuleJava extends MyGameModule {
// **OK**: no manual intervention required.
}
这是否可以在无需手动将 Guice 模块的配置方法复制粘贴到 Gin 模块的情况下实现?例如,这是一种解决方法,但不是我喜欢做的:
/* PlayN GWT Gin module */
public class MyGameModuleHtml extends AbstractGinModule {
@Override
protected void configure() {
// **NOK**: copy-paste the Guice module, as shown below.
bindConstant().annotatedWith(Title.class).to("My game title");
// Other bindings...
}
}
它有效,但至少可以说并不漂亮。
底线:我想在所有 PlayN 项目中使用相同的绑定。
解决方案
所以我所做的是根据答案在我的 Java 主程序中使用 GinModuleAdapter:
Injector injector = Guice.createInjector(new GinModuleAdapter(new MyGameModuleHtml()));
这样我也可以删除核心类中的 Guice 绑定。
【问题讨论】: