Accessing injected dependency in managed bean constructor causes NullPointerException

左心房为你撑大大i 提交于 2019-11-26 16:45:15

Injection can only take place after construction simply because before construction there's no eligible injection target. Imagine the following fictive example:

UserInfoBean userInfoBean;
UserDao userDao = new UserDao();
userInfoBean.setDao(userDao); // Injection takes place.
userInfoBean = new UserInfoBean(); // Constructor invoked.

This is technically simply not possible. In reality the following is what is happening:

UserInfoBean userInfoBean;
UserDao userDao = new UserDao();
userInfoBean = new UserInfoBean(); // Constructor invoked.
userInfoBean.setDao(userDao); // Injection takes place.

You should be using a method annotated with @PostConstruct to perform actions directly after construction and dependency injection (by e.g. Spring beans, @ManagedProperty, @EJB, @Inject, etc).

@PostConstruct
public void init() {
    this.user = dao.getUserByEmail("test@gmail.com");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!