每当我尝试将会话范围的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作为库部署。
我在这里做错了什么?我希望这不是容器错误......
答案 0 :(得分:1)
您无法访问@SessionScoped
构造函数中的@ViewScoped
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