本文介绍了在受管Bean构造函数中访问注入的依赖会导致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("[email protected]"); } // Getters and setters.}在创建bean之后注入DAO对象, c $ c> 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 , @Inject ,etc)。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).@PostConstructpublic void init() { this.user = dao.getUserByEmail("[email protected]");} 这篇关于在受管Bean构造函数中访问注入的依赖会导致NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-08 18:10