0

每次我尝试将会话范围的 bean 注入我的视图范围的 bean 时,调用该 bean 时都会收到 NullPointerException。这个问题与自动实例化会话 bean直接相关吗?

这是我到目前为止所尝试的:

面孔-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>

会话Bean.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 作为库部署。

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

4

1 回答 1

1

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

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

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

更多链接:
为什么使用@PostConstruct?
Spring Injection - 在构造函数中访问注入的对象

于 2013-03-20T15:09:45.140 回答