2013-10-02 193 views
0

我想在JSF上構建一個簡單的博客。但是,我不知道如何將相同的有狀態ejb實例注入到2個不同的託管bean中。我知道注入可以通過使用@ManagedProperty註釋間接完成。類似的東西:注入相同的有狀態ejb實例到不同的managedbeans

@ManagedBean 
@ViewScoped 
public class PostController implements Serializable { 

private static final long serialVersionUID = 1L; 

private Post temporaryPost; 

@ManagedProperty(value = "#{authenticationController}") 
private AuthenticationController authenticationController; 

@Inject 
private PostEJB postEJB; 

public void save() { 
    getTemporaryPost().setAuthor(
      getAuthenticationController().getAuthenticationEJB() 
        .getCurrentSessionUser()); 
    postEJB.create(getTemporaryPost()); 
} 
    } 

我想擺脫

@ManagedProperty的(值= 「#{} authenticationController」) 私人AuthenticationController authenticationController;

和直接噴射AuthenticationEJB,像

@注入私人AuthenticationEJB authenticationEJB;

所以,與其

getAuthenticationController()。getAuthenticationEJB() .getCurrentSessionUser()

我會得到

authenticationEJB.getCurrentSessionUser()

但問題是,這是新的authenticationEJB實例,它不包含當前登錄的用戶(用戶爲空)。同時,authenticationController.authenticationEJB.currentsessionuser包含登錄用戶。

在此先感謝!


Finnaly得到了答案!這很容易:

@ManagedProperty(value = "#{authenticationController.authenticationEJB}") 
private AuthenticationEJB authenticationEJB; 

現在它指向相同的authenticationEJB實例。不過,我相信可能有其他方法可以做到這一點。

+0

有YOUT使用'@ SessionScoped'爲'PostController'中託管bean試過嗎? –

+0

剛剛嘗試過,@SessonScoped沒有幫助。 –

+0

對於EJB,我使用'@ EJB'而不是'@Inject',這可能對你有幫助 –

回答

0

那麼,你得到的答案,但也許幾個音符

  • 你爲什麼不直接與@EJB註解注入你的bean PostController
  • 如果你開發了新的項目,使用CDI beans而不是JSF託管Bean,他們很快就會過時(和整個的Java EE棧傾向於使用CDI無處不在緩慢移動)
  • 那麼你就可以擺脫@ManagedProperty,每個bean (這將基本上是您的應用程序中的任何類)將注入@Inject註釋。同樣的事情適用於EJB,因此CDI可以統一對大多數類型bean的訪問。
  • 一些基本的CDI + JSF教程here
+0

恩,感謝您的建議,我對這堆技術真的很陌生。我曾嘗試注入EJB,但據我瞭解,它爲postController創建了一個新的EJB實例。示例:postController.authenticationEJB包含來自authentificationController.authenticationEJB的不同數據。感謝CDI,不知道一切都如此戲劇性地改變! –

+0

對於'無狀態'bean來說是這樣的,但是你寫道你的bean是'有狀態的',所以你應該在注入的每個bean中獲得相同的實例。 –

+0

我真的很困惑,也許我會明天詳細檢查一下。是的,AuthenticationEJB是有狀態LocalBean。 但是,當我將ManagedProperty(value =#{authenticationController.authenticationEJB})「更改爲EJB時,由於用戶字段中的空值(用戶在這裏是帖子作者),所以帖子無法保存在其他情況下,evrything很好.. –

相關問題