Java EE 6: How to call Stateful Session Bean from Stateless Session Bean?

前端 未结 3 1744
星月不相逢
星月不相逢 2020-12-31 17:45

I have a Stateful Session Bean (SFSB) which acts as authentication module. In the SFSB I store the current user that is logged in. Moreover I have some facades (which are St

3条回答
  •  爱一瞬间的悲伤
    2020-12-31 18:23

    You should not inject a stateful EJB into a stateless EJB. This can have very unpredicatable consequences, because lifecycle of a stateful EJB is started when injected and managed by owning bean. In the worst case, stateless EJB can be reused by application server for different users, which would then access the same stateful EJB. In your case, a user would be identified as a different user.

    Most probably you want to associate a stateful EJB with current HTTP session, which is not done automatically as many people suppose. For more details read section named EJB 3 Is Not Contextual here: Contexts and Dependency Injection article

    In order to associate a stateful EJB with the session, you need to inject stateful EJB into session scoped CDI bean, which can be injected freely into a stateless bean - actually only a stub is injected and session scoped bean (together with the stateful EJB) is created for every new session.

    Maybe even better approach is to extract interface of the stateful bean, and use a CDI producer to create a session scoped implementation of the sateful bean. This way you can also handle the case, when a stateful EJB is automatically removed on an exception in the EJB. In such case, you may want to recreate the EJB within the same session.

提交回复
热议问题