空指针异常。为什么当EmplooyeDAOImpl成为现实?

时间:2015-10-25 20:26:31

标签: jsf nullpointerexception ejb

我有一个简单的.xhtml页面,它只有三个字段(用户名,密码,fullName)和一个按钮,该按钮提交要作为员工对象持久保存的数据。当我尝试它时,我得到错误:

Caused by: java.lang.NullPointerException
    at com.dao.implementation.EmployeeDAOImpl.addEmployee(EmployeeDAOImpl.java:63)
    at com.services.AddEmployeeService.addEmployee(AddEmployeeService.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 36 more

看起来它是由EmployeeDAOImpl类引起的。知道问题出在哪里? EmployeeDAOImpl明确地表现出来。它与实现EmployeeDAO接口的事实有关吗?其余代码如下:

EmployeeDAOImpl

public class EmployeeDAOImpl implements EmployeeDAO{

private static final Logger logger = Logger.getLogger( EmployeeDAOImpl.class.getName());

    @PersistenceContext
    EntityManager em;

    public void addEmployee(Employee employee) throws EmployeeException {

    EntityTransaction tx = em.getTransaction();
    try{
        tx.begin();
        em.persist(employee);
        tx.commit();
    }
    catch(PersistenceException e){
        tx.rollback();
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new EmployeeException();
    }

}

AddEmployeeService

import com.dao.implementation.EmployeeDAOImpl;
import com.exceptions.EmployeeException;
import com.model.Employee;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name = "addEmployeeService")
@RequestScoped
public class AddEmployeeService
{
  private Employee emp = new Employee();

  private EmployeeDAOImpl emDAO = new EmployeeDAOImpl();

  public void addEmployee(){
    try {
        emDAO.addEmployee(emp);
    } catch (EmployeeException ex) {
        Logger.getLogger(AddEmployeeService.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Employee getEmp()
{
    return emp;
}

public EmployeeDAOImpl getEmDAO()
{
    return emDAO;
}

public void setEmp(Employee emp)
{
    this.emp = emp;
}  
}

1 个答案:

答案 0 :(得分:3)

由于您显式实例化EmployeeDAOImpl对象,因此无法注入EntityManager(因为容器不知道您创建了对象)并且您获得了NPE。

您需要显式停止创建这些类型的对象,因为它们需要容器的支持。它们需要是托管对象或EJB,需要注入而不是通过构造函数创建。