How to pass parameters to REST resource using Jers

2019-05-25 06:10发布

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!

3条回答
We Are One
2楼-- · 2019-05-25 06:38

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));
        ....
    }
}
查看更多
小情绪 Triste *
3楼-- · 2019-05-25 06:39

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;
  ...
}
查看更多
甜甜的少女心
4楼-- · 2019-05-25 06:41

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

查看更多
登录 后发表回答