I have information stored in a database (actually a content repository but this shouldn’t matter) which should be presented to all users. Currently I have a Singleton Bean which fetches this information and stores it in a variable. This fetch operation is called every time an update happen on the database so that the variable, representing the database content, is always up to date. Also this variable is used by jsf managed beans to display the information. What I wanted to avoid with this approach is that a new database connection has to be opened for every read-only request. Does this approach make sense or should I use an application scoped managed bean instead? I would then have to call the update method of the managed bean from within an EJB. Is there something wrong with doing this?
I have information stored in a database (actually a content repository but this shouldn’t
Share
If you would like to persist information across all sessions of a given web application in JSF then it is best to use Application Scoped and not use a static singleton.
Here are a few reasons why:
Static fields are based on the class loaded in a specific VM. If your application were to be load balanced or clustered then there is no chance that other application server nodes will have access to the information stored on another servers VM.
ApplicationScoped beans can be serializable, meaning that certain web and application containers have the ability to persist these scoped beans to disk in the event of a server restart. This is dependent on the functionality of your given server however.
Certain application servers have good clustering support as well as sticky sessions and global cluser wide application scope. This will allow sessions to be routed to another server successfully if the current sessions server would unexpectedly go down. Also ApplicationScoped beans would be public and accessible everywhere throughout your application regardless of which node is serving a given request. Again, this is highly dependent on the application containers features and configuration.
Static fields would not only be accessible to every request on a given application’s VM, it will be available to EVERY request on EVERY application running on a given VM. If the application server or web container is running multiple web application and they both utilize the same classes then they could be inadvertently sharing information or clashing with each other. Not a good design choice.
For more information see below:
https://blogs.oracle.com/groundside/entry/application_scope_v_s_static