How to pass parameters to REST resource using Jersey 2.5

风格不统一 提交于 2020-01-02 14:31:22

问题


I have a Java server which serves my clients (Not application server).

Now I'm interested to add REST support. I've initialized a Jetty server and created few REST resources.

My question is: How can I pass parameters at the creation of the REST resources?

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??

Thank you!


回答1:


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;
  ...
}



回答2:


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




回答3:


Another option besides using dependency injection is to instantiate and register the REST endpoint yourself. Jersey allows you to do this in a very similar fashion as dependency injection as shown in Dymtro's example. Borrowing liberally from Dymtro, define your endpoint:

@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));
        ....
    }
}


来源:https://stackoverflow.com/questions/21074013/how-to-pass-parameters-to-rest-resource-using-jersey-2-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!