5

I have a method to start up my application:

public void start() throws IOException {
    final Map<String, String> initParams = new HashMap<String, String>();
    initParams.put("com.sun.jersey.config.property.packages", "com.example");
    threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
}

And I have a Jersey resource class:

@Path("/notification")
public class NotificationResource {
    // HOW DO I INJECT THIS GUY?
    private MySampleCollabolator  mySampleCollabolator;    

    @POST
    public void create() {
        System.out.println("Hello world"); 
    }
}

What is the proper way of handling dependencies? I would like my resources to communicate with other objects, how do I wire them together?

Jason S
  • 184,598
  • 164
  • 608
  • 970
Wojtek B.
  • 927
  • 2
  • 9
  • 17

2 Answers2

6

You can implement InjectableProvider. For example:

@Provider
public class FooProvider
    implements InjectableProvider<Resource, Type> {

    public ComponentScope getScope() {
        return ComponentScope.PerRequest;
    }

    public Injectable getInjectable(ComponentContext ic, Resource resource, Type type) {
        return new Injectable() {
            public Object getValue() {
                return new Foo();
            }
        };
    }
}

and then annotate field in your resource:

@Resource private Foo foo;

Stephan
  • 41,764
  • 65
  • 238
  • 329
ivan.cikic
  • 1,827
  • 1
  • 14
  • 7
1

If you're comfortable using spring, then the best way is to use the jersey spring api module (installed as an additional dependency). It's released in lockstep with Jersey.

The javadoc page has a decent example to get you started.

Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
  • Thanks Sean. Do you have any ideas how to make it work if I am not using XML at all? I start up my app like this: GrizzlyWebContainerFactory.create(baseUri, initParams); Or may be there is a way I could skip using spring? It is a bit over the top for me right now to introduce spring. – Wojtek B. Aug 19 '11 at 12:45