EJB Stateless Session Bean Example

In the previous chapter we discussed the fundamental concepts of EJB. In this chapter we are discussing an EJB Stateless Session Bean  example.

Stateless Session Bean – An overview

Stateless session Bean is a type of session bean , which does not keep a conversational state with calling client.In simple words , if the bean has two business methods in it , the state of the bean when executing first business method will not be retained for the second method. This ensures maximum re usability of a bean component . Because Stateless Session Bean does not keep client specific states.

Stateless Session Bean Life Cycle

A stateless session bean has only two states throughout its entire life cycle.

1)Does not exist state

2)Ready for invocation from client.

The EJB container creates a pool of beans and does the necessary dependency injection. Then , if a method with @PostConstruct annotation is there ,it will be invoked.Now the bean is ready for client invocation.If a method annotated with @PreDestroy is there , then that method will be invoked at the end of client invocation. Now the bean is ready for garbage collection.

EJB Stateless Session Bean Example

Now let us discuss an example. In this case our bean has only one business method. The method returns a String message. The invoking client application accesses the EJB and displays the message in its console.The example uses EJB 3.0 specifications.

The tools and software needed for our application are:

1)Java EE SDK 1.6  – Download link

2)Eclipse Indigo – Download link

3)JBoss-6.0.0.M1 – Download link

If JDK is not installed , install it. Extract and put eclipse and JBoss to suitable locations.

Step by Step description

1) Open  eclipse with suitable workspace.

2)Select File –>New–>EJB Project . The following window will be shown. Give a suitable name for the project. In this case I am giving the name as EJBExample. Select JBoss 6.x as target run time and 3.0 as EJB version.

projectsample1

3)Press Next button  for all coming windows. When the Finish button comes , click it.

4)Now select the Servers tab near eclipse console.

5)Right click  and select New–>Server.

servercreateSelect JBoss 6.x as run time  and click on Next.

6)Locate the server installation and click Next.Add our EJBExample to the server . And then press Finish.

7)Now right click on the ejbModule and New –>Package.

ejbModule

Give a suitable name to the package and then press Finish.(This example is using com.ejbs as package name)

8)Now right click on the newly created package  and select New–>Session Bean.Give class name as ExampleBean and select both remote and local options .Select state type as stateless.

beancreate

Press Next and then Finish.

9)Now add the method public String getMessage() to the remote and local interfaces.

ExampleBeanLocal.java

import javax.ejb.Local;

@Local
public interface ExampleBeanLocal {
public String getMessage();
}

ExampleBeanRemote.java

import javax.ejb.Remote;

@Remote
public interface ExampleBeanRemote {
public String getMessage();
}

10)Paste the methods in ExampleBean.java. It has the business method implemented from remote  and local interfaces.

ExampleBean.java

import javax.ejb.Stateless;

/**
* Session Bean implementation class ExampleBean
*/
@Stateless
public class ExampleBean implements ExampleBeanRemote, ExampleBeanLocal {

public ExampleBean() {

}

@Override
public String getMessage() {
return "This is a message from Stateless Session Bean";
}

}

11)Now start the server (If the project EJBExample is not added to early , we need to add it to the run time).

Once the deployment of EJB is done , the EJB instance will be bound to name space by the container itself.(JNDI concepts were discussed earlier)The details of  beans with JNDI bindings will be displayed in the console.

INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

    ExampleBean/remote – EJB3.x Default Remote Business Interface

    ExampleBean/remote-com.ejbs.ExampleBeanRemote – EJB3.x Remote Business Interface

    ExampleBean/local – EJB3.x Default Local Business Interface

    ExampleBean/local-com.ejbs.ExampleBeanLocal – EJB3.x Local Business Interface

12)Now let us create our  client application. For that create a  Dynamic Web Project with JBoss6.x as target run time.Add the EJBExample project as dependency. And create a class in it .

ExampleBeanClient.java

import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.ejbs.ExampleBeanRemote;

public class ExampleBeanClient {

public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
"org.jboss.naming");
props.setProperty("java.naming.provider.url", "127.0.0.1:1099");

InitialContext ctx = new InitialContext(props);
ExampleBeanRemote exampleBean = (ExampleBeanRemote) ctx
.lookup("ExampleBean/remote");
System.out.println("Message from Bean :" + exampleBean.getMessage());
} catch (NamingException e) {
e.printStackTrace();
}

}

}

The properties object gives the initial properties  to retrieve the already bound bean instance.

12)Now run the client application as a Java Application.

Output

Message from Bean :This is a message from Stateless Session Bean

So we created a stateless session bean and deployed in server.We accessed the bean using remote interface. We can access the EJB using local interface , if we select client and server in the same host.

Understanding Stateless Session Bean Life Cycle

In the above ExampleBean.java  , we implemented only the getMessage() method of remote and home interfaces. If we replace the existing ExampleBean.java with  the new one , which has the methods with @PostConstruct and @PreDestroy annotations, then we can understand the life cycle by analyzing the  server log file (Path : %JBOSS_HOME%/server/default/log ,if we are sing the default configuration as running configuration).

ExampleBean.java

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Session Bean implementation class ExampleBean
*/
@Stateless
public class ExampleBean implements ExampleBeanRemote, ExampleBeanLocal {
private static Logger LOGGER = LoggerFactory.getLogger(ExampleBean.class);

public ExampleBean() {

}

@Override
public String getMessage() {
LOGGER.info("Method getMessage() is invoked by a client");
return "This is a message from Stateless Session Bean";
}

@PostConstruct
public void doAfterStartup() {
LOGGER.info("Bean instance has initilized");
}

@PreDestroy
public void doBeforeCleanup() {
LOGGER.info("Bean will be garbage collected soon..");
}

}

See Related Topics

JNDI

JNDI Tutorial

JMS

JMS Tutorial

EJB

EJB Overview

EJB Stateful Session Bean Example

Stateful Session Bean vs Stateless Session Bean

EJB Message Driven Bean Example