How to choose the right bean scope?
我注意到有不同的bean作用域,比如:
1 2 3 4 5 | @RequestScoped @ViewScoped @FlowScoped @SessionScoped @ApplicationScoped |
每种方法的目的是什么?如何为我的bean选择合适的范围?
介绍
它表示bean的作用域(生存期)。如果您熟悉基本servlet Web应用程序的"幕后"工作,那么这就更容易理解:servlet是如何工作的?实例化、会话、共享变量和多线程。好的。
选择哪个范围完全取决于bean保存和表示的数据(状态)。对于简单和非Ajax表单/演示,使用
对会话/视图/请求范围的数据使用
请注意,不应根据性能影响来选择作用域,除非您的内存占用量确实很低,并且希望完全无状态;您需要专门使用
- 托管bean中视图和请求范围的区别
- 使用JSF面流而不是普通导航系统的优点
- JSF2中的通信-托管bean范围
在您的问题中没有提到,但是(遗留)JSF也支持
jsf
- 在时间间隔后过期特定的托管bean实例
- 什么是无范围bean以及何时使用它?
- JSF 2应用程序中的默认托管bean范围是什么?
闪光范围
最后,JSF还支持Flash范围。它由一个与会话范围中的数据条目相关联的短活动cookie支持。在重定向之前,将在HTTP响应上设置一个cookie,该cookie的值与会话范围中的数据条目唯一关联。重定向后,将检查闪存作用域cookie的存在,并将与cookie关联的数据条目从会话作用域中删除,并将其放入重定向请求的请求作用域中。最后,cookie将从HTTP响应中删除。这样重定向的请求就可以访问在初始请求中准备的请求范围数据。好的。
这实际上不能作为一个托管bean范围来使用,也就是说,没有像
- 如何在重定向页面中显示人脸消息
- 在@viewscoped bean之间传递一个对象,而不使用get-params
- cdi缺少@viewscoped和@flashscoped
好啊。
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.
来源:核心Java服务器面向David Geary和Cay Horstmann的第三版[第51页-第54页]