Learning EJB concepts abstractly is hard. Students need a concrete, minimal example that demonstrates stateful session beans, passivation/activation, and the full EJB lifecycle in action.
The Count Bean is a simple stateful session bean example that maintains a conversational state (an integer counter val). It demonstrates the full EJB development cycle: remote interface, home interface, bean class, deployment descriptor, and client code.
- Remote Interface (
Count): ExtendsEJBObject, declarescount()business method that throwsRemoteException - Bean Class (
CountBean): ImplementsSessionBean, hasvalas conversational state, implementscount()to increment and returnval - Lifecycle Callbacks:
ejbCreate(int val)initializes state,ejbPassivate()serializes to storage,ejbActivate()restores from storage - Home Interface (
CountHome): ExtendsEJBHome, declarescreate(int val)which maps toejbCreate() - Deployment Descriptor: Declares
<session-type>Stateful</session-type>inejb-jar.xml - Client: Looks up Home via JNDI, calls
home.create(10), callscount()to increment
The example shows passivation when pool limit (2 beans) is reached, then activation when beans are reused.
- Stateful: Maintains conversational state (
val) across method calls - Passivation: Bean serialized to storage when pool is full or idle
- Activation: Bean restored from storage when needed again
- Serialiable state:
valis serialiable (primitive int) - JNDI lookup: Client finds Home Object via JNDI, not
new - No
this: Bean usesSessionContext.getEJBObject()to get self-reference
- Built from: Stateful Session Bean — CountBean is a stateful bean
- Built from: Remote Interface — Count interface extends EJBObject
- Built from: Home Interface — CountHome is the factory
- Built from: Passivation — demonstrated when pool limit reached
- Built from: Activation — demonstrated when bean reused
- Builds into: EJB Development Lifecycle — full example of the lifecycle
- Related: SessionContext — provides
getEJBObject()for self-reference - Related: Instance Pooling — pool management triggers passivation
- Stateful cannot be pooled: Unlike stateless, each client gets dedicated bean
- Passivation failure:
valmust be serialiable, or passivation fails thisdanger: Never passthisto other beans—usegetEJBObject()- Pool limit: Container-specific setting controls when passivation occurs
- Server crash: Passivated state may be lost if server crashes