java-我可以使用CDI在Jersey 1.x中@Inject一个类吗?
作者:互联网
我想问的是这个问题,但对于Jersey 1.x:Dependency injection with Jersey 2.0
我正在使用Glassfish 3,CDI和Jersey1.x.我有一个@WebService正在注入这样的类:
@Inject
Foo foo;
我已经在@WebService中对其进行了测试,并且可以正常工作.但是,我的Jersey资源中的同一行代码在尝试使用foo时会抛出NPE.我认为Jersey 1.x忽略了CDI批注.我如何才能像在@WebService中那样进行依赖项注入?
Foo是一个pojo,我的web.xml使用的是ServletContainer:
<servlet>
<servlet-name>JerseyServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
我找到了some help here.问题是我的Foo @Injects拥有了自己的bean(它们实际上是来自其中带有@Provides的类的EJB). resourceContext.getResource(Foo.class);返回Foo的实例,但是foo的@Injected字段为null.
解决方法:
我发现an article可以说明如何执行此操作:
The problem here is, that CDI isn’t in place to instantiate the dependency.
Their[sic] are two solutions for this problem:
- 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批注放在资源上. 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
标签:jersey,cdi,glassfish-3,jersey-1-0,java 来源: https://codeday.me/bug/20191121/2055063.html