Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing injected dependency in managed bean constructor causes NullPointerException

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("[email protected]");
    }

    // 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?

like image 992
Evgeni Dimitrov Avatar asked Apr 17 '12 18:04

Evgeni Dimitrov


1 Answers

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("[email protected]");
}
like image 128
BalusC Avatar answered Oct 02 '22 21:10

BalusC