I typically have this kind of code pattern in my GWT project:
Menu errorMenu = new Menu(user, userController, -1);
Menu searchMenu = new Menu(user, userController, 0);
errorView.setMenu(errorMenu);
searchView.setMenu(searchMenu);
How do I inject a Menu instance in the ErrorView and other “views” using Gin/Guice:
public ErrorView implements View {
// Inject menu instance here
private Menu menu;
}
Such that, I don’t have to manually create and set objects?
Also for the Menu class, how can I inject the “user” and “userController” objects so I don’t have to pass it on each Menu instance every time it is instantiated.
With help of this tutorial http://code.google.com/p/google-gin/wiki/GinTutorial your problem does not look so difficult. There are several steps you should run for injecting menu instance to the View.
Add @Inject annotation to the menu field.
But in this case menu fields will be null during View object initialization (in constructor). Therefore I prefer to add this field to the constructor parametres.
Ofcourse it will not work in case of you have many other parameters in the constructor of ErrorView, because all of them need to be injected as well.
Now we must make sure that GIN knows that menu field in ErrorView should be
injected to
new Menu(user, userController, -1)and another one inSearchView to –
new Menu(user, userController, 0). We can do thisby the several ways:
Add annotations
@Named("searchMenu")and@Named("errorMenu")to your menu fields.or
In your GIN module you should provide the definition of this annotation.
Create your own annotations
@SearchMenuand@ErrorMenuto your menu fields and define them in your module.Annotation sample:
Usage:
or
Then define annotation the way exactly how you defined @Named(“ErrorMenu”):
In some examples I make menu field final and remove setter to it, but if you really need mutable state for menu you can leave it unchanged.