Stateless Session Bean

Stateless Session Bean Tutorial for beginners and professionals. there are 3 types of annotations used in the stateless session bean, Annotations used in Stateless Session Bean, stateless, postconstruction, destroy, Life cycle of Stateless Session Bean, Example of Stateless Session Bean, Create stateless bean component, Create stateless bean client.

Stateless Session Bean

Stateless Session Bean

A stateless Session bean is a business object that represents business logic only. It doesn't have a state (data).

In other words, a conversational state between multiple method calls is not maintained by the container in case of the stateless session bean.

The stateless bean objects are pooled by the EJB container to service the request on-demand.

It can be accessed by one client at a time. In case of concurrent access, EJB container routes each request to a different instance.

Annotations used in Stateless Session Bean

There are 3 important annotations used in stateless session bean:

  1. @Stateless
  2. @PostConstruct
  3. @PreDestroy

Life cycle of Stateless Session Bean

There is only two states of stateless session bean: do not exist and ready. It is explained by the figure given below.


EJB Container creates and maintains a pool of session bean first. It injects the dependency if-then calls the @PostConstruct method if any. Now actual business logic method is invoked by the client. Then, the container calls @PreDestory method if any. Now the bean is ready for garbage collection.



Example of Stateless Session Bean

To develop a stateless bean application, we are going to use Eclipse IDE and glassfish 3 servers.

To create a EJB application, you need to create a bean component and bean client.

1) Create a stateless bean component

To create the stateless bean component, you need to create a remote interface and a bean class.



  1. import javax.ejb.Remote;  
  3. @Remote  
  4. public interface AdderImplRemote {  
  5. int add(int a,int b);  
  6. }  



  1. import javax.ejb.Stateless;  
  3. @Stateless(mappedName="st1")  
  4. public class AdderImpl implements AdderImplRemote {  
  5.   public int add(int a,int b){  
  6.       return a+b;  
  7.   }  
  8. }  

2) Create a stateless bean client

The stateless bean client may be a local, remote or web service client. Here, we are going to create a remote client. It is a console-based application. Here, we are not using dependency injection. The dependency injection can be used with the web-based client only.



  1. import javax.naming.Context;  
  2. import javax.naming.InitialContext;  
  4. public class Test {  
  5. public static void main(String[] args)throws Exception {  
  6.     Context context=new InitialContext();  
  7.     AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");  
  8.     System.out.println(remote.add(32,32));  
  9. }  
  10. }  


Output: 64