I am new to sparkjava and like it overall. However, do new routes/endpoints have to be defined in the main method? For any significant web application, this will result in a very long main method or I need to have multiple main methods (and therefore split server resources among multiple instances).
These two sparkjava documentation pages seem to define routes in the main method: http://sparkjava.com/documentation.html#routes and here http://sparkjava.com/documentation.html#getting-started.
Is there another way to do this that I'm not seeing? Cursory google searching hasn't shown me a better way ...
=========
Here is the full solution I did based on the answer from Andrew. In my opinion, adding endpoints outside of the main method should be part of the sparkjava documentation page:
Main Method:
public static void main(String[] args) {
//Do I need to do something more with the Resource instance so that sparkjava notices it and/or reads the routes?
Resource resource= new Resource(new Service());
}
My resource:
import static spark.Spark.*;
class Resource{
private Service service;
Resource(Service service){
this.service = service;
setupEndpoints();
}
private void setupEndpoints() {
get("/user/:id", "application/json",(request, response)
-> service.find(request.params(":id")), new JsonTransformer());
get("/users", "application/json", (request, response)
-> service.findAll(), new JsonTransformer());
}
}
My service:
public class Service {
public Object find(String id) {
return null;
}
public Object findAll() {
return null;
}
}
My JsonTransformer:
import spark.ResponseTransformer;
public class JsonTransformer implements ResponseTransformer {
@Override
public String render(Object model) throws Exception {
return null;
}
}
Well, spark-java is for people not wanting tons of extra config I guess.
So, I just put and additonal method in the controllers, named declareRoutes where I put the declarations.
For the sample application:
So, in my application I initialize all routes like this:
The declareCatchAllRoute() is just:
Works well enough for my needs, does not require any new abstraction.
HTH
You can set routes where you want. You just need call set up method in main thread. e.g.
Here's a design idea you can use when there are multiple endpoints to configure:
First, create a builder interface:
Now, let's say you have one of many other rest endpoints resources to set up:
Finally, create a RestContext class that will hold the spark instance and will enable you to configure whatever routes you wish:
You should be able to use this context class in your main method (and optionally in your test classes):
Obs.: Since version 2.5, spark java supports multiple instances through the Service.ignite() api.
You can also integrate Spring into your Spark application. This is how I've configured my routes.
This allows me to avoid the setup invocation step in the Main method of the SparkApp.