문제

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.
}

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.

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");
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top