[英]How to pass parameters to REST resource using Jersey 2.5
I have a Java server which serves my clients (Not application server). 我有一台为客户服务的Java服务器(不是应用程序服务器)。
Now I'm interested to add REST support. 现在,我有兴趣添加REST支持。 I've initialized a Jetty server and created few REST resources. 我已经初始化了Jetty服务器并创建了一些REST资源。
My question is: How can I pass parameters at the creation of the REST resources? 我的问题是: 如何在创建REST资源时传递参数?
Normally I would prefer in the constructor of each resource, but I don't control it. 通常,我更喜欢每种资源的构造函数,但我不控制它。
I understand there is a way to inject dependencies. 我了解有一种注入依赖项的方法。 How to do it using Jersey 2.5?? 如何使用Jersey 2.5做到这一点?
Thank you! 谢谢!
Define your Application 定义您的应用
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new FacadeBinder());
register(JacksonFeature.class);
register(MyEndpoint.class);
}
Configure injection 配置注入
public class FacadeBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MyManager.class).to(MyManager.class);
}
}
Inject configured classes in your endpoint 在终端中注入已配置的类
@Path("/jersey")
public class MyEndpoint {
@Inject
MyManager myManager;
...
}
I'm not sure to understand what do you mean with dependencies. 我不确定您对依赖项的含义。
You should check this: https://jersey.java.net/documentation/latest/user-guide.html#d0e1810 您应该检查以下内容: https : //jersey.java.net/documentation/latest/user-guide.html#d0e1810
Another option besides using dependency injection is to instantiate and register the REST endpoint yourself. 除了使用依赖注入之外,另一个选择是自己实例化和注册REST端点。 Jersey allows you to do this in a very similar fashion as dependency injection as shown in Dymtro's example. Jersey允许您以与依赖注入类似的方式执行此操作,如Dymtro的示例所示。 Borrowing liberally from Dymtro, define your endpoint: 从Dymtro大量借用,定义您的端点:
@Path("/jersey")
public class MyEndpoint {
private MyManager myManager;
public MyEndpoint(MyManager myManager) {
this.myManager = myManager;
}
....
}
Define your application: 定义您的应用程序:
public class MyApplication extends ResourceConfig {
public MyApplication(MyManager myManager) {
register(JacksonFeature.class);
register(new MyEndpoint(myManager));
....
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.