Search code examples
javagwtguicegwt-gin

Gin problem using GWT - GWT.create(someClass.class) return different instance every time is called


here is my problem. I m using Gin in a gwt project, i m using GWT.create(SomeClass.class) to get instance ,but the problem is that i want signleton instance and for that purpose i bind that class in the app module to be singleton. Every tome i execute GWT.create(TemplatePanel.class) it returns different instance..why?? Here is snippet of my code. Module

public class AppClientModule extends AbstractGinModule
{
protected void configure()
{
  bind(MainPanel.class).in(Singleton.class);
  bind(TemplatePanel.class).in(Singleton.class);
}
} 

Injector

@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
  MainPanel getMainForm();
  TemplatePanel getTemplateForm();
}

TemplatePanel

public class TemplatePanel extends VerticalPanel
@Inject
public TemplatePanel()
{
  this.add(initHeader());
  this.add(initContent());
}
..

MainPanel

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

.......
}

And the entry point

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);
}

Solution

  • GWT.create(..) does not work with GIN, it just creates an object in a normal GWT way. You should either:

    1. Inject TemplatePanel in MainPanel, or

    2. Instantiate injector (via static method maybe) and then get TemplatePanel.

    I usually have a static reference to injector (since you only need one per app) so I can access it anywhere:

    @GinModules(AppClientModule.class)
    public interface AppInjector extends Ginjector
    {
        AppInjector INSTANCE = GWT.create(AppInjector.class);
    
        MainPanel getMainForm();
        TemplatePanel getTemplateForm();
    }
    

    (Note: constant interface fields are by definition public and static, so you can omit those.)

    Then you'd use:

    TemplatePanel temp = AppInjector.INSTANCE.getTemplateForm();