java.lang.NullPointerException,当我在托管 bean 的构造函数内调用其他 bean 的方法时

发布于 2024-09-16 17:34:25 字数 495 浏览 2 评论 0原文

当我在托管的构造函数内并尝试从其他 bean 访问其他方法时,我得到了 java.lang.NullPointerException。是否有某种规范不允许托管 bean 这样做?

@ManagedProperty(value="#{document}")
private DisplayListController document;

@EJB
DocumentSBean sBean;

public NewUserController() {
    document.list();
} 

上面我只是做了常规的豆子注入,没什么花哨的。 document 是一个 SessionScoped 托管 bean,其方法 list() 仅返回一个 StringNewUserController 是一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

执手闯天涯 2024-09-23 17:34:25

您应该查看 @PostConstruct . 可以在此处找到示例。

当您尝试访问它们时,您的属性并未被设置。您需要等待它们被设置。 Bean 管理通常是:

  1. 创建 Bean
  2. 设置属性

您尝试使用尚未设置的属性,从而导致 NPE。

所以你的代码可以更改为:

public NewUserController() { }

@PostConstruct
public void init() {
    document.list();
}

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:

  1. Create Beans
  2. Set Properties

You're trying to use properties that have not been set, thus resulting in your NPE.

So your code could change to:

public NewUserController() { }

@PostConstruct
public void init() {
    document.list();
}
蹲墙角沉默 2024-09-23 17:34:25

DisplayListController 可能应该配置为使用列表方法上的 @PostConstruct 注释来调用自己的 init 方法

DisplayListController should probably be configured to call its own init method with the @PostConstruct annotation on the list method

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文