Developing an EJB 3 Stateless Session Bean

This tutorial covers the development of an EJB 3 Stateless Session bean. Because JPA Entities and EJB 3 Entities are so similar, developing an EJB 3 Entity Bean is not covered in this tutorial. However, in this tutorial you will learn how to:

  • Create an EJB 3 project
  • Create a stateless session bean
  • Deploy and test the bean

Duration Time: 30 Minutes

Start Tutorial Now

Don't have MyEclipse? Download Now


1. Create an EJB 3 Project

Begin by creating a new EJB 3 project that will include the EJB. 

Note: The project created in this tutorial is available in the Resources section.

  1. Select File>New>Project, and double-click EJB Project.
  2. Type SampleEJBProject in the Project name field.
  3. Accept the default JavaEE 6.0 - EJB 3.1 version, select None for JPA Support, and click Finish. The remaining fields in the wizard are filled in from the MyEclipse EJB project template. This template is defined in the MyEclipse Java Enterprise Project preferences.

    Note: This tutorial uses the default JavaEE 6 version; however, JavaEE 7 is an available option when creating new projects.
    EJB 3 project
    Creating a new EJB project

You can optionally configure any data source you might use for this project to generate EJB3 Entity Beans, but as mentioned earlier, this is not part of this tutorial. See the MyEclipse JPA Tutorial to learn more.

The new project includes the default ejbModule source folder and a sampleejbproject package:

EJB 3 project
Project structure 


2. Create a Stateless Session Bean

Creating a stateless session bean involves defining the bean's interfaces and creating the session bean. When the Session Bean is generated, it implements two interfaces, one for Local calls (in the same VM) and one for Remote calls (Outside VM, over network, etc.). It is possible to have different functions exposed based on the caller (e.g. don't expose methods to Remote invocation that return huge data sets).

For this tutorial, and in some cases, you expose exactly the same information to the Local and Remote callers of the bean. Because of this assumption, the code remains easy to follow by implementing a base interface with all the methods defined in it, that both our Local and Remote versions of the bean extend and our Session Bean implements. The result looks like the following:

EJB 3 application flow
Session bean flow
  1. Right-click the sampleejbproject package, and select New>Interface.
    EJB 3 Java interface
    Creating a new interface
  2. Type IMyBean in the Name field.
  3. Click Add, type java.io. in the Choose interfaces field, and select Serializable. Click OK. This extends Serializable so the application server can better handle the Session Bean if needed.
    EJB 3 Java interface
    Extending the interface with serializable
  4.  Click Finish.
    EJB 3 Java interfaceNew Java interface
  5. The IMyBean interface opens automatically in the Java editor. Add a single method signature to it as shown below, and press CTRL+S to save.
    EJB 3 method
    Adding a method to the interface
  6. Right-click the package, and select New>EJB3 Session Bean.
  7. Type MyBean in the Name field, check the Local and Remote checkboxes to generate local and remote interface versions, and click Finish.
    EJB 3 session bean
    Creating the session bean with local and remote interfacesThe Local and Remote interfaces are added to the project.

    Project structure with the session bean and interfacesThe MyBeanLocal and MyBeanRemote interfaces need to be modified to extend IMyBean as well as add the implementation for doSomething()to MyBean. If you hadn't defined IMyBean, you would have to copy-paste the method definitions from it to both MyBeanLocal and MyBeanRemote to expose those methods. Defining the methods in a single interface makes things a bit easier. As a reminder, you now have this structure:

  8. Double-click MyBean.java, and add the following code before the final bracket to implement the doSomething() method added to the bean interface. Press CTRL+S to save.
  public void doSomething() { 
System.out.println("Hello World!");
}

Also, each of the interfaces need to extend IMyBean. Open MyBeanLocal.java and MyBeanRemote.java and add extends IMyBean to public interface so it looks like the following:

public interface MyBeanLocal extends IMyBean {
}

3. Deploy the Bean

The deploying and running steps are done by using MyEclipse to deploy the bean to a Java EE 6.0-compliant application server.  This tutorial uses Glassfish 3.1.

  1. Right-click the Glassfish server in the Servers view, and select Add/Remove Deployments.
  2. Select SampleEJBProject in the available column, click Add, and click Finish.

    Adding the project to the server
  3. Right-click the server, and select Start if the server is not running.

    The application server starts up and displays messages to the Console view about successfully deploying the Session Bean.

    Console output

    4. Test the Bean

    To test, you need to create a new Java test class in the package.

    1. Right-click the package, and select New>Class.

      Creating a test class
    2. Type MyBeanClient in the Name field, and select the Public static void main checkbox to tell MyEclipse to generate a main method for it. Click Finish.

      Java class detailsBefore adding code to the client and running it, you need to add gf-client.jar to the build path. This JAR is from the Glassfish 3 library folder and contains a customized jndi.properties file that allows direct connection to the Glassfish 3 JNDI context automatically and retrieves the bean with almost no effort.
    3. Right-click the project, and select Build Path>Configure Build Path.
    4. Click the Libraries tab, and click  Add External JARs.

      Adding an external JAR to the build path
    5. Navigate to the Glassfish installation folder, and then the lib folder, and double-click gf-client.jar.
    6. Click OK.

      External JAR added to the build pathNow you are ready to add code to the test client and run it. The actual code, thanks to the JAR just added, is surprisingly simple.
    7. Double-click MyBeanClient.java, and replace the code with the following. Press CTRL+S to save.
    package sampleejbproject;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    public class MyBeanClient {

    public static void main(String[] args) {
    try {
    InitialContext ctx = new InitialContext();
    MyBeanRemote bean = (MyBeanRemote) ctx.lookup(MyBeanRemote.class.getName());
    bean.doSomething();
    }
    catch (NamingException e) {
    e.printStackTrace();
    }
    }
    }

    There are some key things to notice in the code above to make sense of it:

    • The code casts the returned bean not to MyBean but to the interface MyRemoteBean because it is requesting the remote bean from the JNDI context. As mentioned above, the methods exposed by the different Local/Remote interfaces could vary, so you need to stick to the interface you are requesting.
    • Glassfish uses a default JNDI name-binding for EJBs that don't specify one. Look again at the server-log screenshot. Notice the default name is printed out in the log. This default name varies by application server, and most people would use mappedName value of the @Stateless annotation to specify a new binding across all app servers. For example: @Stateless(name="MyBean", mappedName="ejb/MyBean").
    • After you have the bean, you can treat it like a local instance, and simply invoke it.

    Because of how the code for the bean is written (System.out.println), the result is output to the application server Console view in MyEclipse. To see the results of the application, right-click MyBeanClient.java, and select Run As>Java Application from the menu.

    Result of running the test client