background image

The Life Cycle of a Stateful Session Bean

<< Naming Conventions for Enterprise Beans | The Life Cycle of a Message-Driven Bean >>
<< Naming Conventions for Enterprise Beans | The Life Cycle of a Message-Driven Bean >>

The Life Cycle of a Stateful Session Bean

The Life Cycle of a Stateful Session Bean
Figure 20­3
illustrates the stages that a session bean passes through during its lifetime. The
client initiates the life cycle by obtaining a reference to a stateful session bean. The container
performs any dependency injection and then invokes the method annotated with
@PostConstruct
, if any. The bean is now ready to have its business methods invoked by the
client.
While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by
moving it from memory to secondary storage. (Typically, the EJB container uses a
least-recently-used algorithm to select a bean for passivation.) The EJB container invokes the
method annotated @PrePassivate, if any, immediately before passivating it. If a client invokes
a business method on the bean while it is in the passive stage, the EJB container activates the
bean, calls the method annotated @PostActivate, if any, and then moves it to the ready stage.
At the end of the life cycle, the client invokes a method annotated @Remove, and the EJB
container calls the method annotated @PreDestroy, if any. The bean's instance is then ready for
garbage collection.
Your code controls the invocation of only one life-cycle method: the method annotated
@Remove
. All other methods in
Figure 20­3
are invoked by the EJB container. See
Chapter 34,
"Resource Connections"
for more information.
The Life Cycle of a Stateless Session Bean
Because a stateless session bean is never passivated, its life cycle has only two stages: nonexistent
and ready for the invocation of business methods.
Figure 20­4
illustrates the stages of a stateless
session bean.
Does Not
Exist
Ready
1. Create
2. Dependency injection, if any
3. PostConstruct callback, if any
4. Init method, or ejbCreate<METHOD>,
if any
1. Remove
2. PreDestroy callback, if any
Passive
PrePassivate
callback, if any
PostActivate
callback, if any
FIGURE 20­3
Life Cycle of a Stateful Session Bean
The Life Cycles of Enterprise Beans
The Java EE 5 Tutorial · September 2007
642