我创建了一个ejb
@Stateless
@LocalBean
public class BasitBean {
public String helloBasit() {
return "Basit";
} //end of helloBasit()
} //end of class BasitBean
我是从 JSF 调用它的
<h:body>
<h:outputLabel value="#{helloBasit.callBasit()}" />
</h:body>
@ManagedBean
@SessionScoped
public class HelloBasit {
@EJB
private BasitBean basitBean;
/** Creates a new instance of HelloBasit */
public HelloBasit() {
}
public String callBasit() {
return basitBean.helloBasit();
} //end of callBasit()
} //end of class HelloBasit
这段代码工作正常。但是当我像这样更改代码时
<h:body>
<h:outputLabel value="#{helloBasit.label}" />
</h:body>
@ManagedBean
@SessionScoped
public class HelloBasit {
@EJB
private BasitBean basitBean;
String label;
/** Creates a new instance of HelloBasit */
public HelloBasit() {
System.out.println();
String label = basitBean.helloBasit();
System.out.println(label);
}
public BasitBean getBasitBean() {
return basitBean;
}
public void setBasitBean(BasitBean basitBean) {
this.basitBean = basitBean;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
} //end of class HelloBasit
然后我得到了例外
SEVERE: Error Rendering View[/index.xhtml]
com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: pk.mazars.basitMahmood.HelloBasit.
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
......
为什么我得到这个例外?我理解的流程应该是当我的页面遇到#{helloBasit.label}
然后我的构造函数被调用,实例变量被初始化,将bean实例注入basitBean,然后bean方法应该调用。但是在这种情况下,我在 bean 实例中得到了 null,为什么?为什么以前的代码可以工作,但不能?如何从构造函数调用 bean?
谢谢你。