sparkjava:路由必须在main方法中吗? [英] sparkjava: Do routes have to be in main method?
问题描述
我是sparkjava的新手,总体上喜欢它。但是,是否必须在main方法中定义新的路由/端点?对于任何重要的Web应用程序,这将导致非常长的main方法,或者我需要多个main方法(因此,需要在多个实例之间分配服务器资源)。
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).
这两个sparkjava文档页面似乎在主要方法中定义了路由: http://sparkjava.com/documentation.html#routes 和此处 http://sparkjava.com/documentation.html#getting-started 。
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.
还有另一种我看不到的方法吗?游标Google搜索还没有向我展示更好的方法...
Is there another way to do this that I'm not seeing? Cursory google searching hasn't shown me a better way ...
=========
=========
这是我根据安德鲁的回答所做的完整解决方案。我认为,将端点添加到main方法之外应该是sparkjava文档页面的一部分:
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方法:
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());
}
我的资源:
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());
}
}
我的服务:
public class Service {
public Object find(String id) {
return null;
}
public Object findAll() {
return null;
}
}
我的JsonTransformer:
My JsonTransformer:
import spark.ResponseTransformer;
public class JsonTransformer implements ResponseTransformer {
@Override
public String render(Object model) throws Exception {
return null;
}
}
推荐答案
您可以在所需位置设置路线。您只需要在主线程中建立调用方法。例如
You can set routes where you want. You just need call set up method in main thread. e.g.
public static void main(String[] args){
Resource resource= new Resource(new Service());
}
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());
}
}
这篇关于sparkjava:路由必须在main方法中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!