2013-03-24 41 views
0

我有一個ManagedBean gett無狀態bean注入,但它總是給我一個注入空指針。我在這裏做錯了什麼? (I'm學習JSF和它只是一個例子,所以請忽略類等的命名)注入到託管bean的statless bean給出空指針

有兩個不同的罐子(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; 
    } 
} 

無國籍豆

@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> 
+0

ExamServiceBase是一個EJB,所以你試圖通過EJB註釋注入它嗎?我不確定它是否適用於Inject ... – perissf 2013-03-24 18:11:19

+0

@perissf,它的工作原理和它是完全合法的。 @Martin,是'ExamService'和'@ Local'接口?你應該嘗試注入,如果它是 – kolossus 2013-03-24 18:48:52

+0

@kolossus我確實有一個本地接口,這就是我原來使用的,但既沒有,也沒有我的實際實現。兩者都給出空指針例外 – Marthin 2013-03-25 08:38:41

回答

0

我有類似的問題。確保最初在應用程序中有一個文件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"> 

然後嘗試從postcostruct方法使用注入的Bean。在我的情況下,它以這種方式工作。

@PostConstruct 
void init() { 
Exam exam = examService.getSingleExam(); 
} 
+0

今天晚些時候我會試試這個,但是,這個真的看起來像是一個黑客而不是一個可靠的解決方案。 = – Marthin 2013-03-25 08:42:57

+0

今天晚些時候我會試試,但是,它看起來像一個黑客攻擊。任何理由爲什麼這會工作?感謝您的幫助! – Marthin 2013-03-25 08:43:55

+0

@Marthin,這不是黑客,但實際上是CDI的工作要求。您必須在Web-app的WEB-INF中具有beans.xml文件(如果適用)以使注入工作 – kolossus 2013-03-25 10:34:36