【问题标题】:Auto-instantiate session-scoped bean from view-scoped bean从视图范围的 bean 自动实例化会话范围的 bean
【发布时间】:2013-03-20 15:05:48
【问题描述】:

每次我尝试将会话范围的 bean 注入我的视图范围的 bean 时,调用该 bean 时都会收到 NullPointerException。这个问题和auto -instantiate a session bean?直接相关

这是我目前尝试过的:

faces-config.xml

<managed-bean>
    <managed-bean-name>sessionBean</managed-bean-name>
    <managed-bean-class>com.example.SessionBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
    <managed-bean-name>viewBean</managed-bean-name>
    <managed-bean-class>com.example.ViewBean</managed-bean-class>
    <managed-bean-scope>view</managed-bean-scope>
    <managed-property>
        <property-name>sessionBean</property-name>
        <property-class>com.example.SessionBean</property-class>
        <value>#{sessionMBean}</value>
    </managed-property>
</managed-bean>

SessionBean.java:

package com.example;

public class SessionBean {

    public SessionBean() {
        System.out.println("Session is instantiated.");
    }

    public void sayHello() {
        System.out.println("Hello from session");
    }
}

ViewBean.java:

package com.example;

public class ViewBean {

    private SessionBean sessionBean;

    private String text = "Look at me!";

    public ViewBean() {
        System.out.println("View bean is instantiated.");

        sessionBean.sayHello();
    }

    public SessionBean getSessionBean() {
        return sessionBean;
    }

    public void setSessionBean(SessionBean sessionBean) {
        this.sessionBean = sessionBean;
    }

    public String getText() {
        return text;
    }
}

以及index.xhtml的相关内容:

<f:view>
    <h:outputText value="#{viewBean.text}"/>
</f:view>

这就是我得到的:

com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.example.ViewBean.
...
Caused by: java.lang.NullPointerException
    at com.example.ViewBean.(ViewBean.java:12)

这在 weblogic-10.3.6 上运行(或者说不运行),并将随附的 jsf-2-0.war 作为库部署。

我在这里做错了什么?我希望这不是容器错误...

【问题讨论】:

  • 试着用简单的 Java 术语思考:怎么可能在 viewBean = new ViewBean() 之前做 viewBean.setSessionBean(sessionBean)

标签: jsf-2 weblogic-10.x


【解决方案1】:

您无法在@ViewScoped 构造函数中访问@SessionScoped bean。 @SessionScoped bean 将在@ViewScoped bean 的构造函数被调用后设置。 在某种 init 方法中使用@PostConstruct 注解来访问@SessionScoped bean。

public ViewBean() {
  System.out.println("Constructor viewbean");
}

@PostConstruct
public void init() {
  sessionBean.sayHello();
}

更多链接:
Why use @PostConstruct?
Spring Injection - access to the injected object within a constructor

【讨论】:

  • 非常感谢,这当然是有道理的。你不能注入尚未创建的东西。
猜你喜欢
  • 2013-12-30
  • 1970-01-01
  • 2012-05-26
  • 2012-08-28
  • 2012-01-20
  • 2016-01-02
  • 2017-01-22
  • 1970-01-01
  • 2012-12-26
相关资源
最近更新 更多