Accessing injected dependency in managed bean constructor causes NullPointerException
Asked Answered
T

1

12

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?

Tuberculous answered 17/4, 2012 at 18:34 Comment(0)
P
23

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]");
}
Pickmeup answered 17/4, 2012 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.