2

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!

venergiac
  • 7,469
  • 2
  • 48
  • 70
Shvalb
  • 1,835
  • 2
  • 30
  • 60
  • I think it is much simpler to create REST server with Spring, look at this example http://spring.io/guides/gs/rest-service/ This still uses Jersey, but requires a lot less code to create whole REST service. – MariuszS Jan 12 '14 at 11:25
  • I've already created REST service but I only need to pass parameters to every REST resource's constructor. – Shvalb Jan 12 '14 at 16:37
  • Show some code, then will be easier to help – MariuszS Jan 12 '14 at 16:44

3 Answers3

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;
  ...
}
Dmytro
  • 496
  • 7
  • 17
  • This almost looks perfect except that in the 'FacadeBinder' I pass the .class of my custom class instead of creating an instance and passing arguments in constructor. – Shvalb Jan 14 '14 at 05:27
  • You should reconsider programming practice to avoid operator **new** in business code. Consider use of factory to customize instance creation instead. – Dmytro Jan 19 '14 at 20:12
0

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

Vokail
  • 630
  • 8
  • 27
0

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));
        ....
    }
}
Ed Tyrrill
  • 53
  • 8