使用GWT的Gin问题 - 每次调用GWT.create(someClass.class)返回不同的实例

bra*_*ebg 1 java gwt gwt-gin guice

这是我的问题.我在一个gwt项目中使用Gin,我使用GWT.create(SomeClass.class)来获取实例,但问题是我需要signleton实例,为此我将app模块中的该类绑定为singleton.每个tome我执行GWT.create(TemplatePanel.class)它返回不同的实例..为什么?这是我的代码片段.模

public class AppClientModule extends AbstractGinModule
{
protected void configure()
{
  bind(MainPanel.class).in(Singleton.class);
  bind(TemplatePanel.class).in(Singleton.class);
}
} 
Run Code Online (Sandbox Code Playgroud)

注射器

@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
  MainPanel getMainForm();
  TemplatePanel getTemplateForm();
}
Run Code Online (Sandbox Code Playgroud)

TemplatePanel

public class TemplatePanel extends VerticalPanel
@Inject
public TemplatePanel()
{
  this.add(initHeader());
  this.add(initContent());
}
..
Run Code Online (Sandbox Code Playgroud)

mainPanel中

public void onSuccess(List<MyUser> result)
    {
.......
  TemplatePanel temp = GWT.create(TemplatePanel.class);

.......
}
Run Code Online (Sandbox Code Playgroud)

和切入点

private final AppInjector injector = GWT.create(AppInjector.class);
public void onModuleLoad()
{
  MainPanel mf = injector.getMainForm();
  TemplatePanel template = injector.getTemplateForm();
  template.setContent(mf);
  RootPanel.get().add(template);
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ego 7

GWT.create(..)不适用于GIN,它只是以正常的GWT方式创建一个对象.你应该:

  1. 注射TemplatePanelMainPanel,或

  2. 实例化注入器(可能通过静态方法)然后获取TemplatePanel.

我通常有一个静态引用注入器(因为你每个应用程序只需要一个)所以我可以在任何地方访问它:

@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
    AppInjector INSTANCE = GWT.create(AppInjector.class);

    MainPanel getMainForm();
    TemplatePanel getTemplateForm();
}
Run Code Online (Sandbox Code Playgroud)

(注意:常量接口字段根据定义为public和static,因此您可以省略它们.)

那你就用了:

TemplatePanel temp = AppInjector.INSTANCE.getTemplateForm();
Run Code Online (Sandbox Code Playgroud)