我有这个类(JAX-RS/Jersey 和 JPA/Hibernate 的混合):
public class Factory {
@PersistenceContext(unitName = "abc")
EntityManager em;
@Path("/{id}")
@GET
public String read(@PathParam("id") int i) {
return em.find(Employee.class, i).getName();
}
}
这是单元测试:
public class FactoryTest extends JerseyTest {
public FactoryTest() throws Exception {
super("com.XXX");
}
@Test
public void testReadingWorks() {
String name = resource().path("/1").get(String.class);
assert(name.length() > 0);
}
}
这里一切都很好,除了一个:em
在 read()
中是 NULL
。看起来 Grizzly(我将此服务器与 Jersey 测试框架一起使用)没有注入(inject) PersistenceContext
。我在这里做错了什么?
最佳答案
Everything is fine here except one this: em is NULL inside read(). Looks like Grizzly (I'm using this server together with Jersey Test Framework) is not injecting PersistenceContext. What am I doing wrong here?
- 我不确定 Grizzly 是否提供注入(inject)。
- 我不确定“任何”Jersey 资源是否支持注入(inject)(Paul Sandoz 似乎暗示它应该在 this thread 中,但我找不到该声明的明确证据)。
据我所知,最简单的解决方案是将 EntityManager 注入(inject) EJB 3.1 无状态 session Bean (SLSB),它可以直接作为 REST 资源公开(通过使用 JAX- RS 注释)。
另一种选择是使 JAX-RS 资源成为托管 bean 并使用 CDI 进行注入(inject)。这就是 TOTD #124: Using CDI + JPA with JAX-RS and JAX-WS 的方法.
在这两种情况下,我认为您需要使用嵌入式 GlassFish 容器作为 Jersey 测试的容器。
资源
关于java - 通过 Jersey/Grizzly 运行测试时,应该如何以及由谁注入(inject) PersistenceContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814621/