Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

java - How to wire in a collaborator into a Jersey resource?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...