假设您有一个 PlayN 游戏,它在其核心项目中使用 Guice 绑定:
/* 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 项目中使用相同的绑定。
解决方案
所以我所做的是GinModuleAdapter
在我的Java main 中使用,基于答案:
Injector injector = Guice.createInjector(new GinModuleAdapter(new MyGameModuleHtml()));
这样我也可以删除核心类中的 Guice 绑定。