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

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

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

我有一个泽西岛资源类:

 @Path("/notification") public class NotificationResource { // HOW DO I INJECT THIS GUY? private MySampleCollabolator mySampleCollabolator; @POST public void create() { System.out.println("Hello world"); } } 

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

您可以实现InjectableProvider 。 例如:

 @Provider public class FooProvider implements InjectableProvider { 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私人Foo foo;

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

javadoc页面有一个很好的例子可以帮助您入门。