Jsf 访问托管bean构造函数中的注入依赖项会导致NullPointerException
我正在尝试将DAO作为托管属性注入Jsf 访问托管bean构造函数中的注入依赖项会导致NullPointerException,jsf,constructor,nullpointerexception,managed-bean,managed-property,Jsf,Constructor,Nullpointerexception,Managed Bean,Managed Property,我正在尝试将DAO作为托管属性注入 public class UserInfoBean { private User user; @ManagedProperty("#{userDAO}") private UserDAO dao; public UserInfoBean() { this.user = dao.getUserByEmail("test@gmail.com"); } // Getters and setter
public class UserInfoBean {
private User user;
@ManagedProperty("#{userDAO}")
private UserDAO dao;
public UserInfoBean() {
this.user = dao.getUserByEmail("test@gmail.com");
}
// Getters and setters.
}
DAO对象是在创建bean之后注入的,但它在构造函数中为null,因此会导致NullPointerException。如何使用注入的托管属性初始化托管bean?注入只能在构造之后进行,因为在构造之前没有合格的注入目标。想象一下下面这个虚构的例子:
UserInfoBean userInfoBean;
UserDao userDao = new UserDao();
userInfoBean.setDao(userDao); // Injection takes place.
userInfoBean = new UserInfoBean(); // Constructor invoked.
这在技术上根本不可能。事实上,发生的情况如下:
UserInfoBean userInfoBean;
UserDao userDao = new UserDao();
userInfoBean = new UserInfoBean(); // Constructor invoked.
userInfoBean.setDao(userDao); // Injection takes place.
您应该使用带注释的方法在构造和依赖项注入之后直接执行操作,例如Springbeans、@ManagedProperty、@EJB、@Inject等
@PostConstruct
public void init() {
this.user = dao.getUserByEmail("test@gmail.com");
}