Search code examples
javajsfseamjboss7.xconversation-scope

How to store a bean per conversation


Is there a way to store some bean inside the conversation context? I.e for each new conversation, a new separate bean is created belonging to it.


Solution

  • The easiest way to do what you want is to declare a ConversationScoped managed bean or EJB where JSF2 manages the scope.

    There are some good explanations here:

    ... any of which will do a better job than I will. The very short version is that you annotate a bean - which can be a plain POJO that follows the bean conventions - with the @ConversationScoped annotation. You then @Inject a Conversation object, which you can use to begin() and end() conversations. Inject this @ConversationScoped bean into other things. The Conversation.begin and Conversation.end methods control its lifecycle.

    There's a bit much code to just post here, but the above links should help.

    An alternative to @ConversationScoped POJO managed beans can be @Stateful @ConversationScoped EJBs. They can be really handy when you need EJB services in a conversation.

    For some of the conceptual background and detail read the CDI/Weld reference on scopes - and the rest of the CDI/Weld manual. It's really well written and really good.