March 3, 2021
Hot Topics:

Introduction to EJBs: Part 2

  • By Sams Publishing
  • Send Email »
  • More Articles »

Providing Lifecycle Hooks

Remember that the intention of the EJB environment is that you will spend most of your time writing business logic rather than network and database "plumbing." Beyond writing the business logic, the only additional thing the bean writer needs to do is to provide lifecycle "hooks" that allow the container to manage the bean.

Each of the different types of EJB discussed earlier has a slightly different lifecycle, but the common parts are as follows:

  • Bean creation and initialization

  • Bean destruction and removal

  • The saving and restoring of the bean's internal state (if applicable)

The details associated with each type of bean lifecycle will be discussed as they are covered. For now, all you need to know is that

  • An EJB will implement one or more lifecycle interfaces depending on its type. The interfaces (SessionBean, EntityBean, MessageDrivenBean, and SessionSynchronization) are defined in the javax.ejb package.

  • The lifecycle methods will generally begin with ejb so that they can be easily distinguished from the business methods around them, for example, ejbCreate().

Listing 4.3 contains the lifecycle methods in the example AgencyBean.

Listing 4.3 Lifecycle Methods on the AgencyBean

package agency;

import java.rmi.*;
import java.util.*;
import javax.ejb.*;
// Remaining imports removed for clarity

public class AgencyBean implements SessionBean
  private DataSource dataSource;
  private String name = "";

  private void error (String msg, Exception ex) {
    String s = "AgencyBean: " + msg + "\n" + ex;
    throw new EJBException(s);

  public void ejbCreate () throws CreateException {
    try {
      InitialContext ic = new InitialContext();
      dataSource = (DataSource)ic.lookup("java:comp/env/jdbc/Agency");
      name = (String)ic.lookup("java:comp/env/AgencyName");
    catch (NamingException ex) {
      error("Error connecting to java:comp/env/Agency:", ex);

  public void ejbActivate() {

  public void ejbPassivate() {

  public void ejbRemove() {
    dataSource = null;

  private SessionContext ctx;
  public void setSessionContext(SessionContext ctx) {
    this.ctx = ctx;

   // Remaining methods removed for clarity


As you can see, the example AgencyBean implements the SessionBean interface. This means that it must implement the ejbCreate(), ejbRemove(), ejbActivate(), ejbPassivate(), and setSessionContext() methods. The ejbCreate() method takes on the role of constructor in that most of the bean initialization will take place in there. The context passed in setSessionContext() provides a way for the bean to communicate with the container.

This concludes the examination of the bean internals for the time being. You will discover more as you learn about the specific types of EJB later.

Factory Information

For an EJB to be used by a client, the client must create a new instance or discover an existing one. Finding and gaining access to the services of a traditional remote server is relatively simple. Such a server will tend to start when the machine boots, reside in a well-know location, and carry on running until the machine shuts down. However, EJBs are far more dynamic than that. It is the ability to dynamically create and reuse beans that provides the scalability inherent in the EJB model.

To facilitate the creation and discovery of EJBs, each type of EJB provides a home interface. The bean developer will provide an EJB home interface that acts as a factory for that particular EJB. A home interface will extend the javax.ejb.EJBHome interface and will contain the necessary methods identified by the bean developer that allow a client to create, find, or remove EJBs.

There are two ways for a client to get hold of the EJB itself, depending on the type of EJB (Session, Entity, or Message-driven) and the way it is intended to be used. The EJB Home interface can contain one or more create() methods to create a new instance of an EJB. So, for example, you will create a new instance of a Session bean before using it. On the other hand, when you interact with Entity EJBs, you will frequently find existing EJBs using one or more findXXX() methods. The home interface may or may not allow you to remove the bean, depending on bean type and usage.

Listing 4.4 shows the home interface for the example Agency EJB.

Listing 4.4 Home Interface for the Agency Bean

package agency;

import java.rmi.*;
import javax.ejb.*;

public interface AgencyHome extends EJBHome
  Agency create () throws RemoteException, CreateException;


Because the Agency EJB is just a simple wrapper around some JDBC-based functionality and does not maintain any business state, all that is required is a simple creation method—create(). This maps onto the ejbCreate() seen in Listing 4.3. The client will call create() to create an instance of the Agency bean.

The code underlying the home interface will work with the container to create, populate, and destroy EJBs as requested by the client. The effects of the method calls will vary depending on the type of EJB being manipulated. As a result, a request to remove a Session EJB will just result in the EJB being thrown away, while the same request on an Entity EJB may cause underlying data to be removed. The types and effects of different home interface methods are discussed in more detail on subsequent days.

Bean Metadata

The final piece of the EJB jigsaw lies in the provision of configuration information, or metadata, for the EJB. This provides a way of communicating the EJB's requirements and structure to the container. If an EJB is to be successfully deployed, the container will have to be provided with extra information, including

  • An identifier or name for the EJB that can be used to look it up.

  • The bean type (Session, Entity, or Message-driven).

  • Which class is the EJB's remote interface. This interface will typically just be named according to the EJB's functionality, for example, Agency or BankTeller.

  • Which class is the EJB's home interface. The name for an EJB's home interface will typically be derived from its remote interface name. So, for example, the Agency EJB has a home interface called AgencyHome. However, because this is a convention rather than being mandatory, the metadata explicitly indicates the name of the home interface.

  • Which class is the bean itself. Again, the name for the bean will typically be derived from the associated remote interface name. So, for example, the Agency bean is called AgencyBean. However, because this is a convention rather than being mandatory, the metadata explicitly indicates the name of the bean.

  • Any name/value pairs to be provided as part of the bean's environment.

  • Information about any external resources required by the EJB, such as database connections or other EJBs.

All of this essential information is bundled into a deployment descriptor that accompanies the EJB classes. As you might expect, given its recent rise as the most ubiquitous way to define data, the deployment descriptor is defined as an XML document. The deployment descriptor is discussed in more detail soon when examining the packaging of an EJB.

In addition to the essential information, the deployment descriptor can also carry other metadata that you will encounter as you progress:

  • Declarative attributes for security and transactions

  • Structural information bean relationships and dependencies

  • Persistence mapping (if applicable)

You are now nearing the conclusion of this whistle-stop tour of the structure of an EJB. After you have examined how an EJB is created and packaged, you will be ready to deploy and use one.

Monday's installment: What is an EJB and why use them?

Wednesday's installment: How do I create, deploy, and use an EJB?

About the Author

Andy Longshaw is a consultant, writer and educator specializing in J2EE, XML, Web-based technologies and components, particularly the design and architecture decisions required to use these technologies successfully. Andy has been explaining technology for most of the last decade as a trainer and in conference sessions. A wild rumor suggests that some people have managed to stay awake in these sessions. Despite being well educated and otherwise fairly normal, Andy still subjects himself, and his family, to "trial by unpredictability" by watching Manchester City FC far more often than is healthy.

Andy and the other authors work for Content Master Ltd., a technical authoring company in the United Kingdom specializing in the production of training and educational materials. For more information on Content Master, please see their web site at www.contentmaster.com

Source of this material

This is the first of four installments that make up Chapter 4: Introduction to EJBs from the book Sams Teach Yourself J2EE in 21 Days (ISBN:0-672-32384-2) written by Martin Bond, Dan Haywood, Debbie Law, Andy Longshaw, and Peter Roxburgh, published by Sams Publishing.

To access the full Table of Contents for the book

Page 2 of 2

This article was originally published on July 30, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date