java.lang.NullPointerException,当我在托管 bean 的构造函数内调用其他 bean 的方法时
当我在托管的构造函数内并尝试从其他 bean 访问其他方法时,我得到了 java.lang.NullPointerException。是否有某种规范不允许托管 bean 这样做?
@ManagedProperty(value="#{document}")
private DisplayListController document;
@EJB
DocumentSBean sBean;
public NewUserController() {
document.list();
}
上面我只是做了常规的豆子注入,没什么花哨的。 document
是一个 SessionScoped
托管 bean,其方法 list()
仅返回一个 String
。 NewUserController
是一个 RequestScoped
托管 bean。
When I am inside the constructor of a managed and trying to reach out to other methods from other beans, I got java.lang.NullPointerException
. Is there some kind of specification that not allow managed bean to do that?
@ManagedProperty(value="#{document}")
private DisplayListController document;
@EJB
DocumentSBean sBean;
public NewUserController() {
document.list();
}
Above I just do regular bean injection, nothing fancy. document
is a SessionScoped
managed bean that has method list()
which just return a String
. NewUserController
is a RequestScoped
managed bean.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该查看 @PostConstruct . 可以在此处找到示例。
当您尝试访问它们时,您的属性并未被设置。您需要等待它们被设置。 Bean 管理通常是:
您尝试使用尚未设置的属性,从而导致 NPE。
所以你的代码可以更改为:
You should look into @PostConstruct. An example can be found here.
Your properties are not being set when you're trying to access them. You need to wait for them to be set. Bean management typically goes:
You're trying to use properties that have not been set, thus resulting in your NPE.
So your code could change to:
DisplayListController 可能应该配置为使用列表方法上的 @PostConstruct 注释来调用自己的 init 方法
DisplayListController should probably be configured to call its own init method with the @PostConstruct annotation on the list method