Sunday, March 6, 2011

EJB 3 Stateless Session Bean

In this guide I am going to show you how to create an Ejb 3 steteless session bean.
Stateless session beans are used to implements process that could be done in one action, such as a login.
EJB 3 beans look like POJO classes; you do only have to implement the business interface that could be Local or Remote, or both.



From the picture you can see that I created a Remote Interface for my bean by annotating it with the @Remote annotation. It means that the bean could be accessed remotely using this interface. The remote call is provided by the RMI (Remote Method Invocation) call.
Stateless session beans, due to their nature to don't maintain state, could also be exposes as Web Services, because web services as them should not maintain any state, using to annotate the interface with the @Web Service annotation providing the remote call by the Simple Object Access Protocol.
In the next picture I show a simple Stateless session bean:



The only thing we have to do to denote this class as a stateless session bean is annotate it as @Stateless, as I you can see over the class declaration, and implement the business interface we crated. Doing so, the container automatically provides its services to the bean.
The @Stateless annotation has different attributes such as name, mappedName, etc that could be used to set his JNDI name. If omitted, as in my case, his JNDI name is by default the class name.

Another important annotation that we can recognize into the code is the @Resource annotation. It allows us to inject into the bean external resources such as datasources, as I did in my code. The name parameter of the resource annotation, denotes the ENV name of the component, while the mappedName parameter denotes the Global name of the component, that is the JNDI name used inside the container in which this resource has been deployed.

Let's see now how the client calls and uses the bean I have just created:


I created only a Servlet on which I Injected the bean using his remote business interface.
The only thing to do to use a bean from a servlet or another client is to inject it using the @EJB annotation and then use the business methods provided by it.

In the next guides I will show you other important components and annotations of EJB 3.

No comments:

Post a Comment