On Tue, 2006-01-17 at 21:00 -0500, Tom Butler wrote:
> Where I need help understanding is how to set up the scope for the
> managed beans and data access object. Currently, I have the backing
> bean within the session scope (using the facesconfig.xml file). My
> main question is how to set up the scope for the Data Access Object -
> currently I do not have it as a managed bean within facesconfig.xml.
> Instead I am creating a new instance within the backing bean:
>
>
>
> private DbInsert dbinsert = new DbInsert();
>
>
>
> Is this the best way to do this? Will the DBInsert object now be tied
> to the session scope of the backing bean (i.e., when backing bean is
> deleted, the DbInsert object will be deleted from session scope as
> well.)
The bean is of session scope, so it will continue to exist until the
user's session is deleted, or the backing bean is explicitly removed
from the session. And of course the reference to the DbInsert object
will live for the same time.
>
>
> Ideally I would like the data access object to be available as a
> shared object throughout the life of the application. When I was
> programming using a servlet approach, I would have created a servlet
> to load on startup. Now that I'm using java server faces, I'm
> confused about the scope / how to efficiently set up a data access
> object that I want to be available to all backing beans in the
> application.
> tnanks for any help understanding this.
I would strongly recommend you avoid using session scope for backing
beans (ie beans that provide presentation logic to a specific page). The
bean is only relevant when the user is accessing certain pages, but will
continue to exist until the user's session times out. Unless your app is
just a few pages that's not a good idea.
I recommend you put your DB access functionality in a bean that is
declared as a managed bean of application scope.
You can then declare your backing beans as request scope, and use a
managed-property declaration to connect the backing beans to the Db
access bean.
<managed-bean>
<managed-bean-class>example.DBInserter</managed-bean-class>
<managed-bean-name>dbInserter</managed-bean-name>
<scope>application</scope>
</managed-bean>
<managed-bean>
<managed-bean-class>example.SomeBackingBean</managed-bean-class>
<managed-bean-name>bean1</managed-bean-name>
<scope>request</scope>
<managed-property>
<name>inserter</inserter>
<value>#{dbInserter}</value>
</managed-property>
</managed-bean>
Managed bean objects are created only when they are actually needed, so
the dbInserter object will be created when the first page that
references it (directly or indirectly) is viewed. If this is not
desirable, and you prefer it to be created on webapp startup then you
could use a ServletContextListener to create it.
This page might be useful:
http://wiki.apache.org/myfaces/AccessingOneManagedBeanFromAnother
Regards,
Simon