将 EJB 注入 JAX-RS(RESTful 服务) [英] Inject an EJB into JAX-RS (RESTful service)
问题描述
我正在尝试通过注释将无状态 EJB 注入到我的 JAX-RS Web 服务中.不幸的是,EJB 只是 null
,当我尝试使用它时,我得到一个 NullPointerException
.
I'm trying to inject a Stateless EJB into my JAX-RS webservice via annotations. Unfortunately the EJB is just null
and I get a NullPointerException
when I try to use it.
@Path("book")
public class BookResource {
@EJB
private BookEJB bookEJB;
public BookResource() {
}
@GET
@Produces("application/xml")
@Path("/{bookId}")
public Book getBookById(@PathParam("bookId") Integer id)
{
return bookEJB.findById(id);
}
}
我做错了什么?
这是关于我的机器的一些信息:
Here is some information about my machine:
- 玻璃鱼 3.1
- Netbeans 6.9 RC 2
- Java EE 6
你们能展示一些有效的例子吗?
Can you guys show some working example?
推荐答案
我不确定这是否可行.所以要么:
I am not sure this is supposed to work. So either:
选项 1:使用注入提供程序 SPI
实现将执行查找并注入 EJB 的提供程序.见:
Implement a provider that will do the lookup and inject the EJB. See:
com.sun.jersey:jersey-server:1.17 的示例:
Example for com.sun.jersey:jersey-server:1.17 :
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.ws.rs.ext.Provider;
import java.lang.reflect.Type;
/**
* JAX-RS EJB Injection provider.
*/
@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {
public ComponentScope getScope() {
return ComponentScope.Singleton;
}
public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
if (!(t instanceof Class)) return null;
try {
Class c = (Class)t;
Context ic = new InitialContext();
final Object o = ic.lookup(c.getName());
return new Injectable<Object>() {
public Object getValue() {
return o;
}
};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
选项 2:使 BookResource 成为 EJB
@Stateless
@Path("book")
public class BookResource {
@EJB
private BookEJB bookEJB;
//...
}
见:
选项 3:使用 CDI
@Path("book")
@RequestScoped
public class BookResource {
@Inject
private BookEJB bookEJB;
//...
}
见:
这篇关于将 EJB 注入 JAX-RS(RESTful 服务)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!