我试图注入一个DAO作为托管属性.
public class UserInfoBean { private User user; @ManagedProperty("#{userDAO}") private UserDAO dao; public UserInfoBean() { this.user = dao.getUserByEmail("test@gmail.com"); } // Getters and setters. }
创建bean后注入DAO对象,但在构造函数中为空,因此导致NullPointerException.如何使用注入的托管属性初始化托管bean?
注射只能在施工后进行,因为在施工前没有合格的注射目标.想象下面的虚构例子:
原文链接:https://www.f2er.com/javaschema/281358.htmlUserInfoBean 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.
您应该使用注释为@PostConstruct
的方法在构建和依赖关系注入之后直接执行操作(例如,Spring beans,@ManagedProperty,@EJB,@Inject等).
@PostConstruct public void init() { this.user = dao.getUserByEmail("test@gmail.com"); }