Jsf 2 从视图范围bean自动实例化会话范围bean

Jsf 2 从视图范围bean自动实例化会话范围bean,jsf-2,weblogic-10.x,Jsf 2,Weblogic 10.x,每次我尝试将会话范围的bean注入到视图范围的bean中时,调用所述bean时都会得到一个NullPointerException。这个问题与 以下是我迄今为止所做的尝试: faces-config.xml <managed-bean> <managed-bean-name>sessionBean</managed-bean-name> <managed-bean-class>com.example.SessionBean</

每次我尝试将会话范围的bean注入到视图范围的bean中时,调用所述bean时都会得到一个NullPointerException。这个问题与

以下是我迄今为止所做的尝试:

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>
ViewBean.java:

package com.example;

public class SessionBean {

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

    public void sayHello() {
        System.out.println("Hello from session");
    }
}
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>
它在weblogic-10.3.6上运行(或者说不运行),附带了部署为库的jsf-2-0.war


我做错了什么?我希望这不是一个容器bug…

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

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

@PostConstruct
public void init() {
  sessionBean.sayHello();
}
更多链接:


非常感谢,这当然有道理。您无法注入尚未创建的内容。请尝试用简单的Java术语思考:在
viewBean.setSessionBean(sessionBean)
之前,如何才能执行
viewBean=newviewBean()
public ViewBean() {
  System.out.println("Constructor viewbean");
}

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