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(MainPane开发者_如何学Pythonl.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);
}
GWT.create(..)
does not work with GIN, it just creates an object in a normal GWT way. You should either:
Inject
TemplatePanel
inMainPanel
, orInstantiate 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();
GWT.create simply calls new XXX where XXX is the class literal you passed to it. It does however does some magic when the XXX class has some rules in a module defined for it, aka Deferred Binding. I fyou can Gwt.create(YYY) and theres a rule that says if user agent is Internet Explorer 2 use ZZZ then it will.
精彩评论