我有一个ManagedBean,它获得一个无状态bean注入,但它总是给我一个空指针注入。我哪里做错了?(我正在学习JSF,这只是一个例子,所以请忽略类的命名等)
有两个不同的jar (web.jar和services.jar)
托管bean
@ManagedBean
@RequestScoped
public class HelloPB
{
@Inject
private ExamServiceBase examService;
private String name = "";
public String getName()
{
Exam exam = examService.getSingleExam();
return exam.getName();
}
public void setName(final String name)
{
//this.name = name;
}
public String getHello()
{
if ( name == null || name.length() < 1 )
{
return null;
}
return "Hello " + name;
}
}
无状态bean
@Stateless
public class ExamServiceBase implements ExamService{
@PersistenceContext(name="QuestifyPersistUnit")
private EntityManager em;
public Exam getExam(String id){
return em.find(Exam.class, id);
}
public Exam getSingleExam(){
return em.find(Exam.class, "9E69F3EE-AE9E-4D53-B531-35504EDA450F");
}
}
index.xhtml
<h:body>
<h:outputScript name="jsf.js" library="javax.faces" target="body">
</h:outputScript>
<h1>JSF 2 Demo</h1>
<h:form>
<h:inputText id="name" value="#{helloPB.name}">
<f:ajax render="helloTextOutput" />
</h:inputText>
<h:commandButton value="Say Hi via Ajax">
<f:ajax execute="name" render="helloTextOutput" />
</h:commandButton>
<h:outputText id="helloTextOutput" value="#{helloPB.hello}" />
</h:form>
</h:body>
我也遇到过类似的问题。首先确保应用程序中有一个文件WEB-INF/beans.xml。它也可以是一个空文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org /2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
然后尝试从后构造方法使用注入的Bean。在我的例子中,它是这样工作的。
@PostConstruct
void init() {
Exam exam = examService.getSingleExam();
}