我注意到有不同的 bean 范围,例如:
@RequestScoped
@ViewScoped
@FlowScoped
@SessionScoped
@ApplicationScoped
每个的目的是什么?如何为我的 bean 选择合适的范围?
我注意到有不同的 bean 范围,例如:
@RequestScoped
@ViewScoped
@FlowScoped
@SessionScoped
@ApplicationScoped
每个的目的是什么?如何为我的 bean 选择合适的范围?
它代表 bean 的范围(生命周期)。如果您熟悉基本 servlet Web 应用程序的“幕后”工作,这将更容易理解:servlet如何工作?实例化、会话、共享变量和多线程。
@Request/View/Flow/Session/ApplicationScoped
一个@RequestScoped
bean 的生命周期与单个 HTTP 请求-响应周期一样长(请注意,Ajax 请求也算作单个 HTTP 请求)。@ViewScoped
只要您通过回发调用返回null
/void
没有任何导航/重定向的操作方法的回发与同一个 JSF 视图交互,一个bean 就存在。@FlowScoped
只要您在流配置文件中注册的指定视图集合中导航,bean 就会存在。一个@SessionScoped
bean 的生命周期与建立的 HTTP 会话一样长。@ApplicationScoped
只要 Web 应用程序运行,bean 就会存在。请注意,CDI@Model
基本上是 的原型,@Named @RequestScoped
因此适用相同的规则。
选择哪个范围仅取决于 bean 持有和表示的数据(状态)。用于@RequestScoped
简单和非 ajax 表单/演示文稿。用于@ViewScoped
支持 ajax 的丰富动态视图(基于 ajax 的验证、渲染、对话框等)。用于@FlowScoped
收集分布在多个页面上的输入数据的“向导”(“问卷调查”)模式。用于@SessionScoped
客户端特定数据,例如登录用户和用户首选项(语言等)。用于@ApplicationScoped
应用程序范围的数据/常量,例如每个人都相同的下拉列表,或没有任何实例变量且只有方法的托管 bean。
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. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. 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). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
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.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean
package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean
annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. @javax.enterprise.context.ApplicationScoped
: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. @javax.enterprise.context.SessionScoped
: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. @javax.enterprise.context.ConversationScoped
: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin()
and Conversation.end()
. These methods should called explicitly, either to start or end the life of a bean.
4. @javax.enterprise.context.RequestScoped
: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. @javax.faces.flow.FlowScoped
: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. @javax.faces.view.ViewScoped
: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
- @SessionScoped
- @RequestScoped
- @ApplicationScoped
- @ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]