Accessing injected dependency in managed bean constructor causes NullPointerException

痴心易碎 提交于 2019-11-26 06:03:31

问题


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?


回答1:


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");
}


来源:https://stackoverflow.com/questions/10196982/accessing-injected-dependency-in-managed-bean-constructor-causes-nullpointerexce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!