The main class used as the bootstrapping class
In this second example, instead of retrieving the router and
the server from the Guice context, we let Guice inject them inside
our App class. The App class is, in other words,
now part of the Guice context!
public class App {
public static void main(String[] args) {
Injector guice = Guice.createInjector(new SpincastDefaultGuiceModule(args) {
@Override
protected void configure() {
super.configure();
bind(App.class).in(Scopes.SINGLETON);
}
});
App app = guice.getInstance(App.class);
app.start();
}
private final IServer server;
private final IDefaultRouter router;
@Inject
public App(IServer server, IDefaultRouter router) {
this.server = server;
this.router = router;
}
public void start() {
this.router.GET("/").save(new IDefaultHandler() {
@Override
public void handle(IDefaultRequestContext context) {
context.response().sendPlainText("In index!");
}
});
this.server.start();
}
}
Explanation :
-
1 : We will use the
Appmain class not only as the class containing themain(...)method, but also as the bootstrapping class... -
5-12 : Inside the
main(...)method, we create the Guice context using the providedSpincastDefaultGuiceModulemodule, but we also extend it, inline, to bind theAppclass too (line 10)! -
14-15 :
We get the
Appinstance from Guice and we call thestart()method on it! Since theAppinstance is now managed by Guice, the required dependencies will be injected automatically and there is no need to manually retrieve the server or the router from Guice anymore. -
21-25 : The contructor
that Guice will use (Note the
@Injectannotation). -
27 : The
start()method we call once the Guice context is created. -
29-34 : We add a
GETroute for the"/"index page, here again using an inline handler. - 37 : We start the server.