Auto-instantiate session-scoped bean from view-scoped bean

℡╲_俬逩灬. 提交于 2019-12-11 20:14:33

问题


Every time I try to inject a session-scoped bean into my view-scoped beans, I get a NullPointerException when calling said bean. This problem is directly related to auto -instantiate a session bean?

Here is what I tried so far:

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;
    }
}

and the relevant content of index.xhtml:

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

And this is what I get:

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

This runs (or rather doesn't run) on weblogic-10.3.6 with the shipped jsf-2-0.war deployed as a library.

What am I doing wrong here? I'm hoping this is not a container bug...


回答1:


You cannot access the @SessionScoped bean in the @ViewScoped constructor. The @SessionScoped bean will be set AFTER the constructor of the @ViewScoped bean has been called. Use the @PostConstruct annotation in some kind of init method to access the @SessionScoped bean.

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

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

Further Links:
Why use @PostConstruct?
Spring Injection - access to the injected object within a constructor



来源:https://stackoverflow.com/questions/15527304/auto-instantiate-session-scoped-bean-from-view-scoped-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!