A Hill of Beans

Deploying an application across a number of servers poses some of the most daunting programming problems you're ever likely to face. In addition to implementing accurate business logic, reliable database transactions, trustworthy security, and efficient load balancing, your server-side software must remain robust and responsive even when servers and network connections fail unexpectedly.

Deploying an application across a number of servers poses some of the most daunting programming problems you’re ever likely to face. In addition to implementing accurate business logic, reliable database transactions, trustworthy security, and efficient load balancing, your server-side software must remain robust and responsive even when servers and network connections fail unexpectedly.

Solving these problems is not only difficult, it’s imperative. Mission-critical applications such as reservation systems, banking, and electronic commerce require always-on access. Any downtime means loss of business.

Such large scale business applications, commonly referred to as “enterprise computing,” forces developers to bring out the big guns: expensive hardware, lots of bandwidth, replication, fail-over schemes, and hefty coding. But just like characters in a Brothers Grimm fairy tale, Java programmers go into this battle armed with a handful of beans. Well, very special beans: Enterprise Java Beans (or EJB), to be exact.

This month, let’s look at Enterprise Java Beans, or EJB. Developed by Sun Microsystems, EJB has been widely accepted as a standard model for developing and deploying complex business systems. Using a set of classes and interfaces from the Java 2 Enterprise Edition (J2EE) javax.ejb package, developers can create, assemble, and deploy components into any server system that implements the EJB specification.

EJB is a broad and complex topic, and an extensive introduction is impossible to present in this small space. Instead, let’s look at some basics and at a small example that will prepare you for some other EJB-related topics coming up in future columns and features.

Aboard the Enterprise

A typical enterprise computing project includes a large and often disparate collection of machines, operating systems, and networks. For example, an enterprise system might include: a graphical Web client; a non-interactive, XML-based Web service; several Linux servers working in tandem with HTTP, SMTP, and instant-messaging servers; and a legacy mainframe database.

Given such a diverse configuration — common in enterprise applications — a great deal of code is required to connect all of the components together. That code is commonly referred to as “middleware,” a kind of software plumbing that connects components to each other and exchanges information via messages, database queries, and packages like RMI (Remote Method Invocation).

For many enterprise projects, programmers have designed their own middleware. Unfortunately, designing and developing middleware requires a great deal of time and effort, not to mention specialized expertise that is often completely unrelated to the business at hand. Indeed, middleware projects can often consume teams (and budgets), leaving the business stagnant.

So, instead of building, many projects choose to buy “off-the-shelf,” pre-built middleware that offers most of the infrastructure required for battle-tested enterprise requirements. These systems are often called “component transaction monitors (CTMs)” or more commonly, “application servers.”

Application servers automatically manage concurrency, transactions, load balancing, security, and resources. While application developers still need to be aware of these facilities, they don’t have to explicitly implement them when using an application server.

As Richard Monson-Haefel says in his book, “Enterprise Java Beans,” (O’Reilly & Associates, Inc., 2001), think of an application server as if it were a relational database: “As a developer using a relational database, you might design the table layouts, decide which columns are primary keys, and define indexes and stored procedures, but you don’t develop the indexing algorithm, the SQL parser, or the cursor-management system.”

Given an application server, you can focus on the design and development of your business objects without having to waste thousands of hours developing the infrastructure in which the objects operate. Conceptually, Enterprise Java Beans are business objects.

Beans, Beans, They’re Good for a Start

To be more precise, Enterprise Java Beans are reusable, portable software components written in Java. Using a set of classes and interfaces from the javax.ejb package, developers can create, assemble, and deploy standardized components. (Here, standardized means that components conform to the EJB specification.)

As long as a component is EJB-compliant, it can be used in any application server that also conforms to the EJB specification. In fact, deploying a bean across application servers is consistent as well: simply bundle the bean’s classes and a configuration file into an archive, and copy the archive to the server.

Once a bean is deployed, the application server places it in an EJB container. Containers intercede between clients and components, providing services (transparently) to both, including transaction support, security, network communication, and resource pooling. The container intercepts all method calls to the bean, and captures all data returned by the bean to a caller. (Like beans, containers are part of the J2EE model. See the sidebar “The J2EE Model” for more information.)

The J2EE Model

Figure One: The three parts of the J2EE model

The J2EE application model divides enterprise applications into three fundamental parts: components, containers, and connectors. Components are the key focus of application developers, while system vendors implement containers and connectors to conceal complexity and promote portability.

Containers intercede between clients and components, providing services transparently to both, including transaction support and resource pooling.

Container mediation allows many component behaviors to be specified at deployment time, rather than in program code.

Connectors sit beneath the J2EE platform, defining a portable service API to plug into existing enterprise vendor offerings. Connectors promote flexibility by enabling a variety of implementations of specific services.

In this arrangement, the application server shoulders a lot of the work that might otherwise be expected of a bean. To pick one particularly useful example, if the bean is an entity bean — an object that holds data and methods that modify and manipulate the data — the application server makes sure that the data is persisted. No additional code is required in the EJB to serialize the data, retrieve it later, or recover from data corruption, server crashes, or similar disasters.

Let’s look at an example enterprise bean and a client that makes use of it. Deploying the sample project requires a J2EE SDK and an EJB application server (and perhaps some server-specific deployment configuration).

You can download a J2EE SDK for free from Sun Microsystems at http://java.sun.com. More sophisticated, commercial development environments such as Borland JBuilder 8 Enterprise and Sun ONE Studio Enterprise Edition are also available for J2EE development on Linux.

If you need an application server, one of the best choices is OpenEJB, an open source EJB container designed to be incorporated in to other middleware technologies such as Web servers and Java servlet engines. OpenEJB includes its own lightweight application server that can be used to test EJB projects locally or over a network. OpenEJB was founded by David Blevins and Richard Monson-Haefel. OpenEJB has been used in WebObjects, OpenCCM, and OpenORB, and the project has recently released version 0.90. You can download the code from the project’s home page at http://openejb.sourceforge.net.

Mr. Formula Bean

Our example project uses an Enterprise Java Bean to manipulate a price based on a secret formula. The bean, FormulaBean (shown in Listing One), contains two methods: getSecretFormula(), which returns a floating-point number that should be used as a multiplier on a price, and getCount(), which returns the number of times the formula has been retrieved in the lifetime of the object.

Listing One: The FormulaBean session bean

package com.prefect.ejb;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class FormulaBean implements SessionBean {
private int count = 0;
private SessionContext con;

public void setSessionContext(SessionContext inCon) {
con = inCon;

public float getSecretFormula() {
return 1.025F;

public int getCount() {
return count;

public void ejbActivate() { // do nothing

public void ejbCreate() { // do nothing

public void ejbPassivate() { // do nothing

public void ejbRemove() { // do nothing

FormulaBean is a session bean, one of three kinds of beans defined in the EJB 2.0 specification. The other two kinds of beans are entity beans and message-driven beans.

Session beans are ideally used to represent some action to be taken, such as calculating a price based on a proprietary business formula or translating legacy data into XML prior to presentation as a Web service.

Entity beans typically represent a real-world object such as a car in a rental lot, a customer, or even a place. Since the properties of real-world objects change — a quantity, a location, a balance — entity beans are typically persisted in a database.

Message-driven beans (added in the EJB 2.0 specification) coordinate tasks between session beans and entity beans.

Here, the example project only uses a session bean.

Session beans are created by implementing the javax. ejb.SessionBean interface. This interface contains several methods that are called by an application server during the bean’s life cycle, including ejbCreate() when the bean is created, ejbRemove() when it’s destroyed, and setSessionContext(), which is called to associate the bean with the context in which it is running. The context is represented by the javax.ejb.SessionContext class and can be used to query the application server from within the bean.

The SessionBean interface also contains two life cycle methods that are used by beans that must save their state over time: ejbActivate() and ejbPassivate(). These methods are called by the application server hosting the bean and will never be called by another bean or a client of the bean.

The object that implements the SessionBean interface should also contain the methods that accomplish the work of the bean. As mentioned earlier, the FormulaBean class has the getSecretFormula() and getCount() methods. These are extremely simple methods for the purposes of brevity, but a real-world commerce application would presumably include much more sophisticated pricing strategies than the one demonstrated in getSecretFormula(), which simply marks up everything 0.25%.

Clients that use a bean don’t make use of it directly — again, requests are intercepted benevolently by the application server so it can take care of all of the bean’s middleware needs. To give clients something to work with, two interfaces must be implemented: a remote interface (a subclass of javax.ejb. EJBObject) that’s used by any external client, and a local interface (a subclass of javax.ejb.EJBLocalObject) that’s used by clients running in the same application server.

Beans offer local and remote interfaces for performance reasons. One EJB bean can use another bean in the same server context at a considerably faster clip than an external client can. These interfaces, presented in Listing Two and Listing Three, contain signatures for the two publically callable methods of FormulaBean. These interfaces are nearly identical.

Listing Two: The bean’s remote interface

package com.prefect.ejb;

import java.rmi.RemoteException;
import javax.ejb.EJBObject;

public interface Formula extends EJBObject {
public int getCount() throws RemoteException;
public float getSecretFormula() throws RemoteException;

Listing Three: The bean’s local interface

package com.prefect.ejb;

import javax.ejb.EJBLocalObject;

public interface FormulaLocal extends EJBLocalObject {
public int getCount();
public float getSecretFormula();

Two additional interfaces must be created so that clients can create instances of the bean. Because this isn’t actually possible, since clients never work directly with the beans, two kinds of interfaces are offered: a home interface that creates EJB objects for remote clients, and a local home interface that creates them for local objects. These are shown in Listing Four (FormulaHome is a subclass of class javax.ejb.EJBHome) and Listing Five (FormulaLocalHome, a subclass of javax.ejb.LocalHome). Both of these include create() method signatures that are used to create objects that act as proxies for FormulaBean objects.

Listing Four: Create a bean from a remote client

package com.prefect.ejb;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface FormulaHome extends EJBHome {
Formula create() throws RemoteException, CreateException;

Listing Five: Create a bean from a local client

package com.prefect.ejb;

import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;

public interface FormulaLocalHome extends EJBLocalHome {
FormulaLocal create() throws CreateException;

Finally, the bean must be deployed on an application server in a JAR file along with all of its interfaces and a deployment descriptor, an XML file that establishes how the bean functions in the server’s EJB container. The descriptor file, ejb.jar, is shown in Listing Six. Most of the format echoes what’s been described here — it’s reasonably self-documenting — aside from tags establishing that it’s a stateless session bean with transactions managed by the container.

Listing Six: The bean’s deployment descriptor

<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc.//DTD Enterprise
JavaBeans 2.0//EN”


Listing Seven contains an example client that makes use of the FormulaBean Enterprise Java Bean. EJB clients implemented with Java can use two Sun technologies for finding and calling these beans: JNDI and RMI-IIOP (the Java Naming and Directory Interface and the Remote Method Invocation over the Internet Inter-ORB Protocol, respectively).

Listing Seven: A client that uses FormulaBean

import com.prefect.ejb.*;
import java.util.Properties;
import javax.ejb.CreateException;
import javax.naming.*;
import java.rmi.RemoteException;
import javax.rmi.*;

public class ExampleClient {
public static void main(String[] arguments) {
Properties pro = System.getProperties();
try {
Context con = new InitialContext(pro);
Object object = con.lookup(“FormulaHome”);
FormulaHome fh = (FormulaHome) PortableRemoteObject.narrow(
object, FormulaHome.class);
Formula pricer = fh.create();
float price = 10.50F * pricer.getSecretFormula();
System.out.println(“The final price is ” + price);
System.out.println(“The secret pricing bean has been used ” +
pricer.getCount() + ” times.”);
} catch (CreateException cre) {
System.out.println(“Create exception: ” + cre.getMessage());
} catch (NamingException nme) {
System.out.println(“Naming exception: ” + nme.getMessage());
} catch (RemoteException rme) {
System.out.println(“Remote exception: ” + rme.getMessage());

Much More Than a Hill of Beans

While EJB may free you from the arduous task of creating middleware, you’ll still have to learn how to create individual Java components that interact with application servers in standard ways. An enterprise project may consist of numerous beans interacting with each other, external applications, servers, and databases.

If you’re interested in tackling more of EJB, read the J2EE specification (available on Sun’s official Web site at http://java.sun.com/j2ee) or one of the many books that explores the technology in detail, such as “Mastering Enterprise JavaBeans, Second Edition,” by Ed Roman, Scott Ambler, and Tyler Jewell or “Enterprise Java Beans,” by Richard Monson-Haefel.

Rogers Cadenhead is a Web application developer. To contact Cadenhead, visit his weblog at http://www.cadenhead.org/workbench. The source code for this month’s Java Matters column can be found online at http://www.linux-mag.com/downloads/2003-02/java.

Comments are closed.