How to store a bean per conversation
-
26-06-2021 - |
質問
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.
解決
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:
- http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html
- http://www.ibm.com/developerworks/java/library/j-jsf2fu-0710/index.html#cdi
- http://www.theserverside.com/tip/Dependency-Injection-in-Java-EE-6-Conversations-Part-4
- http://www.andygibson.net/blog/article/cdi-conversations-part-1/
- http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/
- http://blog.goyello.com/2011/06/08/jee6-cdi-and-conversation-scope/
... 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.