06 - Stateful Session Beans

Stateful Session Beans

In this section we will introduce, how to create Stateful Session Beans and the various lifecycle events that are provided by the bean.

Bean Creation

Same as Stateless beans, Stateful session beans consists of 1 class, the bean class and 2 interfaces, local and remote. The class is required and the interfaces are optional.

Bean Class

Marking a class as a Stateful session bean requires annotating the class by the annotation @Stateful.

Example of bean class:

import javax.ejb.Stateful;

@Stateful
public class ShopCartBean {

}

The previous lines will create a stateless bean and will be registered in the JNDI trees as “ShopCartBean”, you can override the default name by providing a value to the name attribute on the Stateful annotation, as an example:

import javax.ejb.Stateful;

@Stateful(name="ShopCart")
public class ShopCartBean {

}

That way the bean will be registered in the JNDI tree with name “ShopCart” instead of “ShopCartBean”.

Local Interface / Remote Interface

The rules applied to Stateless Session Beans are valid here also, you use the same annotations (@Remote/@Local) to declare the remote and local interfaces.

Stateful Bean Lifecycle

Provided callback methods by the Stateful Beans are:

  • @PostConstruct: This method is called, once all dependency injection on the bean class finishes and it indicates that the bean is ready for methods invocation. The method can be used to allocate the resources needed by the bean object to function correctly (i.e. Network connections, database connections... etc.).
  • @PreDdestroy: This method is called before destroying the bean object and can be used to release all the reserved resources by the bean object.
  • @PrePassivate: This method is called before moving the bean object to passive state. Here the developer should release all the reserved resources of the bean and  prepare the bean state for storage persistent.
  • @PostActivate: This method is called after the bean moves from the passivated state. Here you should reallocate the resources, released during the passivation action.
  • @Remove: This method is the only method that gets called by the client and not by the container. The method marks the bean for removal. Once the bean is marked for removal, the container invokes the method annotated by @PreDestroy if exists and then destroys the bean object.

The following is a state diagram that visualizes the stateful session bean lifecycle:

 

Like us on Facebook