如何将协作者连接到Jersey资源?

时间:2011-08-19 12:19:05

标签: java jersey

我有一种启动应用程序的方法:

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

我有一个Jersey资源类:

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

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

处理依赖项的正确方法是什么?我想要我的资源 与其他对象进行通信,如何将它们连接在一起?

2 个答案:

答案 0 :(得分:6)

您可以实施InjectableProvider。例如:

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

然后在资源中注释字段:

  

@Resource private Foo foo;

答案 1 :(得分:1)

如果您习惯使用spring,那么最好的方法是使用jersey spring api模块(作为附加依赖项安装)。它与泽西岛一同发布。

javadoc page有一个很好的例子可以让你开始。