【发布时间】:2019-02-21 11:43:08
【问题描述】:
我正在尝试部署一个战争文件以在 WildFly Swarm 上运行。在执行 GET 请求时,会发生 NullPointerException,因为注入失败并且引用显然为 null。
SomeDao.java
import java.util.List;
import java.util.UUID;
import javax.ejb.Local;
@Local
public interface SomeDao {
public List<MyEntity> listAll();
public void store(MyEntity entity);
}
SpecializedDao.java
import java.util.List;
import java.util.UUID;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class SpecializedDao implements SomeDao {
@PersistenceContext(unitName="primary")
protected EntityManager entityManager;
public SpecializedDao() {}
@Override
public List<MyEntity> listAll() {
return this.entityManager
.createQuery("SELECT entity FROM MyEntity entity", MyEntity.class)
.getResultList();
}
@Override
public void store(MyEntity entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
}
}
然后,我需要注入一个 SpecializedDao 实例的端点。
MyEndpoint.java
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Stateless
@Path("/something")
public class MyEndpoint {
@EJB
private SomeDao dao;
@GET
@Path("/test")
@Produces({MediaType.APPLICATION_JSON})
public Response test() {
MyEntity testEntity = new MyEntity("something", "something");
dao.store(testEntity);
return Response.ok("All done!").build();
}
}
beans.xml
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.2" bean-discovery-mode="annotated">
</beans>
NullPointerException 在 dao.store(testEntity) 处启动,因为 dao 引用了一个空对象。我很确定 persistence.xml 文件是正确的,因为 EntityManager 在另一个测试用例上工作,所以我认为问题在于注入。
我哪里做错了?
【问题讨论】: