Stateless Session bean is a business object that represents business logic only. It doesn’t have state (data).
In other words, conversational state between multiple method calls is not maintained by the container in case of 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 different instance.
Annotations used in Stateless Session Bean
There are 3 important annotations used in stateless session bean:
- @Stateless
- @PostConstruct
- @PreDestroy
Life cycle of Stateless Session Bean
There is only two states of stateless session bean: does 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, container calls @PreDestory method if any. Now bean is ready for garbage collection.
Example of Stateless Session Bean
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
1) Create stateless bean component
To create the stateless bean component, you need to create a remote interface and a bean class.
File: AdderImplRemote.java
package com.javatpoint; import javax.ejb.Remote; @Remote public interface AdderImplRemote { int add(int a,int b); }
File: AdderImpl.java
package com.javatpoint; import javax.ejb.Stateless; @Stateless(mappedName="st1") public class AdderImpl implements AdderImplRemote { public int add(int a,int b){ return a+b; } }
2) Create stateless bean client
The stateless bean client may be local, remote or webservice client. Here, we are going to create remote client. It is console based application. Here, we are not using dependency injection. The dependency injection can be used with web based client only.
File: AdderImpl.java
package com.javatpoint; import javax.naming.Context; import javax.naming.InitialContext; public class Test { public static void main(String[] args)throws Exception { Context context=new InitialContext(); AdderImplRemote remote=(AdderImplRemote)context.lookup("st1"); System.out.println(remote.add(32,32)); } }
Output
Output: 64
Leave A Comment