问题描述
我想我问的是这个问题,但针对Jersey 1.x:依赖注入使用Jersey 2.0
I think I'm asking this question but for Jersey 1.x: Dependency injection with Jersey 2.0
我正在使用Glassfish 3,CDI和Jersey1.x.我有一个@WebService
,它正在注入这样的类:
I'm using Glassfish 3, CDI and Jersey 1.x. I have a @WebService
that is injecting a class like this:
@Inject
Foo foo;
我已经在@WebService
中对其进行了测试,并且可以正常工作.但是,当我尝试使用foo
时,Jersey资源中的同一行代码会引发NPE.我认为Jersey 1.x忽略了CDI批注.我如何才能像在@WebService
中那样进行依赖项注入?
I've tested this in the @WebService
and it works. But the same line of code in my Jersey resource throws a NPE when it tries to use foo
. I think Jersey 1.x is ignoring the CDI annotations. How can I get dependency injection working like it does in my @WebService
?
Foo
是一个pojo,而我的web.xml使用的是ServletContainer:
Foo
is a pojo and my web.xml is using the ServletContainer:
<servlet>
<servlet-name>JerseyServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
我在这里找到了一些帮助.问题是我的Foo
@Inject
拥有自己的bean(它们实际上是EJB,它们来自其中包含@Provides
的类). resourceContext.getResource(Foo.class);
返回Foo
的实例,但是foo
的@Inject
ed字段为空.
I've found some help here. The problem is my Foo
@Inject
s its own beans (they're actually EJBs that come from a class with @Provides
in it). resourceContext.getResource(Foo.class);
returns an instance of Foo
, but foo
's @Inject
ed fields are null.
推荐答案
我发现一篇文章,其中介绍了如何执行此操作:
I found an article that explains how to do this:
- 让CDI实例化依赖关系,但让Jersey管理它 可以使用
@ManagedBean
和特定于Jersey的注释来实现. - 让CDI实例化依赖关系,然后让CDI管理它. 可以使用
@RequestScoped
或其他CDI特定注释来实现.
- Let CDI instantiate the dependency, but let Jersey managed it This can be achived using
@ManagedBean
and a Jersey specific annotation. - Let CDI instantiate the dependency and let CDI manage it. This can be achieved using
@RequestScoped
or other CDI specific annotations.
我选择了第一个选项,并将javax.annotation.ManagedBean
注释放在我的资源上. 这里是一个例子:
I chose the first option and put the javax.annotation.ManagedBean
annotation on my resource. Here's an example:
package com.coderskitchen.thegreeter.rest;
import com.coderskitchen.thegreeter.greetings.GreetingService;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@Path("/greet")
@ManagedBean
public class Greeter {
@Inject
GreetingService gs;
@GET
@Path("{name}")
public String greetSomeone(@PathParam("name") String name) {
return gs.greetSomeone(name);
}
}
*我也发现了这篇官方文章,实际上并没有什么用: http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-advanced004.htm
* Also I found this official article, which actually isn't as useful: http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-advanced004.htm
这篇关于我可以使用CDI在Jersey 1.x中@Inject一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!