How To Choose The Right Bean Scope? (JSF) : @Request/View/Flow/Session/Applicationscoped
How To Choose The Right Bean Scope? (JSF) : @Request/View/Flow/Session/Applicationscoped
(JSF)
Reference: https://stackoverflow.com/questions/7031885/how-to-choose-the-right-bean-scope
INTRODUCTION
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with
"under the covers" working of a basic servlet web application: How do servlets work? Instantiation,
sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
Which scope to choose depends solely on the data (the state) the bean holds and represents.
1. A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax
request counts as a single HTTP request too).
Use @RequestScoped for simple and non-ajax forms/presentations.
Abusing a @RequestScoped bean for view scoped data would make view scoped data to
be reinitialized to default on every single (ajax) postback, causing possibly non-working
forms (see also points 4 and 5 here).
2. A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks
which call action methods returning null/void without any navigation/redirect.
Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering,
dialogs, etc).
Abusing a @ViewScoped bean for request, session or application scoped data for
application scoped data does not affect the client, but it unnecessarily occupies server
memory and is plain inefficient.
3. A @FlowScoped bean lives as long as you're navigating through the specified collection of views
registered in the flow configuration file.
Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data
spread over multiple pages.
5. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI
@Model is basically a stereotype for @Named @RequestScoped, so same rules apply.
Use @ApplicationScoped for application wide data/constants, such as dropdown lists
which are the same for everyone, or managed beans without any instance variables and
having only methods.
Abusing an @ApplicationScoped bean for session/view/request scoped data would
make it to be shared among all users, so anyone else can see each other's data which is
just plain wrong.
Note that the scope should rather not be chosen based on performance implications, unless you really
have a low memory footprint and want to go completely stateless; you'd need to use exclusively
@RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that
when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in
separate backing beans in a scope matching the data's scope. The beans can just access each other via
@ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.