在托管 bean 构造函数中访问注入的依赖项会导致 NullPointerException [英] Accessing injected dependency in managed bean constructor causes NullPointerException
问题描述
我正在尝试将 DAO 作为托管属性注入.
I'm trying to inject a DAO as a managed property.
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对象,但它在构造函数中为null
,因此导致NullPointerException
.如何使用注入的托管属性初始化托管 bean?
The DAO object is injected after the bean is created, but it is null
in the constructor and therefore causing NullPointerException
. How can I initialize the managed bean using the injected managed property?
推荐答案
注入只能发生在构建之后,因为构建之前没有符合条件的注入目标.想象一下下面这个虚构的例子:
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.
您应该使用带有 @PostConstruct
注释的方法 在构建后直接执行操作和依赖注入(例如通过 Spring bean、@ManagedProperty
、@EJB
、@注入
等).
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");
}
这篇关于在托管 bean 构造函数中访问注入的依赖项会导致 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!