In general, you want to create a custom Guice module for your application, so you can bind custom components.
This is what we are going to do in this tutorial.
We will also create a controller so our Route Handlers
are not defined inline but have their
own dedicated method.
First, we add the latest version of the org.spincast:spincast-default
Maven artifact to our pom.xml
(or build.gradle
) :
<dependency> <groupId>org.spincast</groupId> <artifactId>spincast-default</artifactId> <version>2.2.0</version> </dependency>
Let's then create our controller :
public class AppController { public void index(DefaultRequestContext context) { JsonObject user = context.json().create(); user.set("name", "Stromgol"); user.set("age", 42); context.response().sendJson(user); } }
This controller contains one Route Handler
: "index". A
Route Handler
is a method that receives, as a parameter, an object implementing
RequestContext.
In this simple handler, we create a "user" object as a JsonObject
and we send it as "application/json"
.
Now, let's create a custom Guice module, so we can bind our components :
public class AppModule extends SpincastGuiceModuleBase { @Override protected void configure() { // Binds our controller bind(AppController.class).in(Scopes.SINGLETON); // ... binds all our other application components here } }
Finally, let's bootstrap and start the application! We do that in the standard main(...)
method, using the Bootstrapper :
public class App { public static void main(String[] args) { Spincast.configure() .module(new AppModule()) .init(args); } @Inject protected void init(Server server, DefaultRouter router, AppController ctrl) { router.GET("/").handle(ctrl::index); server.start(); } }
Explanation :
main(...)
method is the entry point of our application.
Spincast.configure()
starts the bootstrapper, so we can configure and initialize our application.
init()
method will create the Guice
context using the default plugins and our custom module, will bind the current
App
class in the context and will load it.
Route
for the index page
using a method reference targeting our controller's "index" method as
the Route Handler
. Spincast is going to call this method each time a GET
request
for the index page is received.
Download this application, and run it by yourself :
mvn clean package
java -jar target/spincast-demos-better-2.2.0.jar
The application is then accessible at http://localhost:44419
Try the Supercalifragilisticexpialidocious "Hello World!" demo, for an improved version!
Try the Quick "Hello World!" demo, for an easier version!