Jump to content

Jakarta Enterprise Beans

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Arjant (talk | contribs) at 21:49, 10 April 2010 (→‎Types: Clarified and corrected info for stateless and stateful session beans. Added information about the singleton session bean.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Simple EJB2 Architecture

Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications.

The EJB specification is one of several Java APIs in the Java EE. EJB is a server-side model that encapsulates the business logic of an application. The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999[1] and enhanced under the Java Community Process as JSR 19 (EJB 2.0), JSR 153 (EJB 2.1) and JSR 220 (EJB 3.0).

The EJB specification intends to provide a standard way to implement the back-end 'business' code typically found in enterprise applications (as opposed to 'front-end' interface code). Such code was frequently found to address the same types of problems, and it was found that solutions to these problems are often repeatedly re-implemented by programmers. Enterprise JavaBeans were intended to handle such common concerns as persistence, transactional integrity, and security in a standard way, leaving programmers free to concentrate on the particular problem at hand.

Accordingly, the EJB specification details how an application server provides:

Additionally, the Enterprise JavaBean specification defines the roles played by the EJB container and the EJBs as well as how to deploy the EJBs in a container.


Rapid adoption followed by criticism

This vision was persuasively presented by EJB advocates such as IBM and Sun Microsystems, and Enterprise JavaBeans were quickly adopted by large companies. Problems were quick to appear, however, and the reputation of EJBs began to suffer as a result. Some developers felt that the APIs of the EJB standard were far more complex than those developers were used to. An abundance of checked exceptions, required interfaces, and the implementation of the bean class as an abstract class were all unusual and counter-intuitive for many programmers. Granted, the problems that the EJB standard was attempting to address, such as object-relational mapping and transactional integrity, are complex. However many programmers found the APIs to be just as difficult if not more so, leading to a widespread perception that EJBs introduced complexity without delivering real benefits.

In addition, businesses found that using EJBs to encapsulate business logic brought a performance penalty. This is because the original specification only allowed for remote method invocation through CORBA (and optionally other protocols), even though the large majority of business applications actually do not require this distributed computing functionality. The EJB 2.0 specification addressed this concern by adding the concept of local interfaces which could be called directly without performance penalties by applications that were not distributed over multiple servers. It was introduced largely to address the performance problems that existed with EJB 1.0.[2]

The complexity issue, however, continued to hinder EJB's acceptance. Although high-quality developer tools made it easy to create and use EJBs by automating most of the repetitive tasks, these tools did not make it any easier to learn how to use the technology. Moreover, a counter-movement had grown up on the grass-roots level among programmers. The main products of this movement were the so-called 'lightweight' (i. e. in comparison to EJB) technologies of Hibernate (for persistence and object-relational mapping) and Spring Framework (which provided an alternate and far less verbose way to encode business logic). Despite lacking the support of big businesses, these technologies grew in popularity and were adopted more and more by businesses who had become disillusioned with EJBs.

EJBs were promoted by Sun's Java Pet Store demo Java BluePrints. The use of EJBs was controversial and influential Java EE programmers such as Rod Johnson took positions in response to Java Pet Store that sought to deemphasize EJB use. Sun itself produced an alternative called Java Data Objects. Later, EJBs, Java Data Forms, and many of the ideas underlying Hibernate were combined to form EJB 3.0 which included the Java Persistence API and Plain Old Java Objects (POJOs). EJB 3.0 was less heavy weight than EJB 2.0 and provided more choices to developers.

Reinventing EJBs

Gradually an industry consensus emerged that the original EJB specification's primary virtue — enabling transactional integrity over distributed applications — was of limited use to most enterprise applications, and the functionality delivered by simpler frameworks like Spring and Hibernate was more useful. Accordingly, the EJB 3.0 specification (JSR 220) was a radical departure from its predecessors, following this new paradigm. It shows a clear influence from Spring in its use of POJOs, and its support for dependency injection to simplify configuration and integration of heterogeneous systems. Gavin King, the creator of Hibernate, participated in the EJB 3.0 process and is an outspoken advocate of the technology. Many features originally in Hibernate were incorporated in the Java Persistence API, the replacement for entity beans in EJB 3.0. The EJB 3.0 specification relies heavily on the use of annotations, a feature added to the Java language with its 5.0 release, to enable a much less verbose coding style.

Accordingly, in practical terms EJB 3.0 is very nearly a completely new API, bearing little resemblance to the previous EJB specifications.

Example

The following shows a basic example of what an EJB looks like in code:

@Local
public interface CustomerServiceLocal {
   void addCustomer(Customer customer);
}

@Stateless 
public class CustomerService { 
  
  @PersistenceContext 
  private EntityManager entityManager; 
    
  public void addCustomer(Customer customer) { 
    entityManager.persist(customer); 
  } 
}

The above defines a local interface and the implementation of a service class for persisting a Customer object (via O/R mapping). The EJB takes care of managing the persistence context and the addCustomer() method is transactional and thread-safe by default. As demonstrated, the EJB focussed only on business logic and persistence and knows nothing about any particular presentation.

Such an EJB can be used by a class in e.g. the web layer as follows:

@Named
@RequestScoped
public class CustomerBacking {

   @EJB CustomerServiceLocal customerService;

   public String addCustomer() {
      customerService.addCustomer(customer);
      context.addMessage(...); // abbreviated for brevity
      return "customer_overview";
   }
}

The above defines a JSF backing bean in which the EJB is injected by means of the @EJB annotation. Its addCustomer method is typically bound to some UI component, like a button. Contrary to the EJB, the backing bean does not contain any business logic or persistence code, but delegates such concerns to the EJB. The backing bean does know about a particular presentation, of which the EJB had no knowledge.

Types

An EJB container holds two major types of beans:

  • Session Beans that can be either "Stateful", "Stateless" or "Singleton" and can be accessed via either a Local (same JVM) or Remote (different JVM) interface. All sessions beans support asynchronous execution for all views (local/remote).
  • Message Driven Beans (also known as MDBs or Message Beans). MDBs also support asynchronous execution, but via messaging paradigm.

Stateful Session Beans are business objects having state: that is, they keep track of which calling client they are dealing with throughout a session and thus access to the bean instance is strictly limited to only one client at a time. Stateful session beans' state may be persisted (passivated) automatically by the container to free up memory after the client hasn't accessed the bean for some time. The JPA extended persistence context is explicitly supported by Stateful Session Beans [3]. As an example, checking out in a web store might be handled by a stateful session bean that would use its state to keep track of where the customer is in the checkout process.

Stateless Session Beans are business objects that do not have state associated with them. However, access to a single bean instance is still limited to only one client at a time and thus concurrent access to the bean is prohibited. This makes a stateless session bean automatically thread-safe. Instance variables can be used during a single method call to the bean, but the contents of those instance variables are not guaranteed to be preserved across method calls. Instances of Stateless Session beans are typically pooled. If a second client accesses a specific bean right after a method call on it made by a first client has finished, it might get the same instance. The lack of overhead to maintain a conversation with the calling client makes them less resource-intensive than stateful beans. Sending an e-mail to customer support might be handled by a stateless bean, since this is a one-off operation and not part of a multi-step process.

Singleton Session Beans are business objects having a global shared state. Concurrent access to the one and only bean instance can be controlled by the container (Container-managed concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC). CMC can be tuned using the @Lock annotation, that designates whether a read lock or a write lock will be used for a method call. Additionally, Singleton Session Beans can explicitly request to be instantiated when the EJB container starts up, using the @Startup annotation. Loading a global daily price list that will be the same for every user might be done with a singleton session bean, since this will prevent the application having to do the same query to a database over and over again.

Message Driven Beans were introduced in the EJB 2.0 specification that is supported by Java EE 1.3 or higher. The message bean represents the integration of JMS (Java Message Service) with EJB to create an entirely new type of bean designed to handle asynchronous JMS or other type of messages. Message Driven Beans are business objects that behave primarily asynchronously. That is, they handle operations that do not require an immediate response. For example, a user of a website clicking on a "keep me informed of future updates" box may trigger a call to a Message Driven Bean to add the user to a list in the company's database. (This call is asynchronous because the user does not need to wait to be informed of its success or failure.) These beans may subscribe to JMS (Java Message Service) message queues or message topics. They were added in the EJB 2.0 specification to allow event-driven processing inside EJB Container. Unlike other types of beans, MDB does not have a client view (Local/Remoteinterfaces), i. e. clients can not look-up an MDB instance. It just listens for any incoming message on e.g. a JMS queue (or topic) and processes them automatically. Only JMS support is required by the Java EE spec, but Message Driven Beans can support other messaging protocols. Such protocols may be asynchronous but can also be synchronous.

Previous versions of EJB also used a type of bean known as an Entity Bean. These were distributed objects having persistent state. Beans in which their container managed the persistent state were said to be using Container-Managed Persistence (CMP), whereas beans that managed their own state were said to be using Bean-Managed Persistence (BMP). Entity Beans were replaced by the Java Persistence API in EJB 3.0, though as of 2007, CMP 2.x style Entity beans are still available for backward compatibility. As of EJB 3.1, JPA has been completely separated to its own spec and EJB will focus only on the "core session bean and message-driven bean component models and their client API" [4].

Other types of Enterprise Beans have been proposed. For instance, Enterprise Media Beans (JSR 86) address the integration of multimedia objects in Java EE applications.

Execution

EJBs are deployed in an EJB container within the application server. The specification describes how an EJB interacts with its container and how client code interacts with the container/EJB combination. The EJB classes used by applications are included in the javax.ejb package. (The javax.ejb.spi package is a service provider interface used only by EJB container implementations.)

With EJB 2.1 and earlier, each EJB had to provide a Java implementation class and two Java interfaces. The EJB container created instances of the Java implementation class to provide the EJB implementation. The Java interfaces were used by client code of the EJB.

The two interfaces, referred to as the Home and the Remote interface, specified the signatures of the EJB's remote methods. The methods were split into two groups:

Class methods
Not tied to a specific instance, such as those used to create an EJB instance (factory method) or to find an existing entity EJB (see EJB Types, above). These were declared by the Home interface.
Instance methods
These are methods tied to a specific instance. They are placed in the Remote interface.

Because these are merely Java interfaces and not concrete classes, the EJB container must generate classes for these interfaces that will act as a proxy in the client. Client code invokes a method on the generated proxies that in turn places the method arguments into a message and sends the message to the EJB server.

Transactions

EJB containers must support both container managed ACID transactions and bean managed transactions. Container-managed transactions use a declarative syntax for specifying transactions in the deployment descriptor.

Events

JMS (Java Message Service) is used to send messages from the beans to client objects, to let clients receive asynchronous messages from these beans. MDB can be used to receive messages from client applications asynchronously using either a JMS Queue or a Topic.

Naming and directory services

Clients of the EJB locate the Home Interface implementation object using JNDI. The Home interface may also be found using the CORBA name service. From the home interface, client code can find entity beans, as well as create and delete existing EJBs.

Security

The EJB Container is responsible for ensuring the client code has sufficient access rights to an EJB.

Deployment

The EJB specification defines a mechanism that allows EJBs to be deployed in a consistent manner regardless of the specific EJB platform that is chosen. Information about how the bean should be deployed (such as the name of the home or remote interfaces, whether and how to store the bean in a database, etc.) are specified in the deployment descriptor.

The deployment descriptor is an XML document having an entry for each EJB to be deployed. This XML document specifies the following information for each EJB:

  • Name of the Home interface
  • Java class for the Bean (business object)
  • Java interface for the Home interface
  • Java interface for the business object
  • Persistent store (only for Entity Beans)
  • Security roles and permissions
  • Stateful or Stateless (for Session Beans)

EJB containers from many vendors require more deployment information than that in the EJB specification. They will require the additional information as separate XML files, or some other configuration file format. An EJB platform vendor generally provides their own tools that will read this deployment descriptor, and possibly generate a set of classes that will implement the Home and Remote interfaces.

Since EJB3.0 (JSR 220), the XML descriptor is replaced by Java annotations set in the Enterprise Bean implementation (at source level), although it is still possible to use an XML descriptor instead of (or in addition to) the annotations. If an XML descriptor and annotations are both applied to the same attribute within an Enterprise Bean, the XML definition overrides the corresponding source-level annotation.

Version history

EJB 3.1, final release (2009-12-10)

JSR 318. The purpose of the Enterprise JavaBeans 3.1 specification is to further simplify the EJB architecture by reducing its complexity from the developer's point of view, while also adding new functionality in response to the needs of the community:

Topics under consideration:

  • Local view without interface
  • .war packaging of EJB components
  • EJB Lite: definition of a subset of EJB
  • Portable EJB Global JNDI Names
  • Singletons
  • Application Initialization and Shutdown Events
  • EJB Timer Service Enhancements
  • Simple Asynchrony

EJB 3.0, final release (2006-05-11)

JSR 220 - Major changes: This release made it much easier to write EJBs, using 'annotations' rather than the complex 'deployment descriptors' used in version 2.x. The use of home and remote interfaces and the ejb-jar.xml file were also no longer required in this release, having been replaced with a business interface and a bean that implements the interface.

EJB 2.1, final release (2003-11-24)

JSR 153 - Major changes:

  • Web service support (new): stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference.
  • EJB timer service (new): Event-based mechanism for invoking EJBs at specific times.
  • Message-driven beans accepts messages from sources other than JMS.
  • Message destinations (the same idea as EJB references, resource references, etc.) has been added.
  • EJB query language (EJB-QL) additions: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD.
  • XML schema is used to specify deployment descriptors, replaces DTDs

EJB 2.0, final release (2001-08-22)

JSR 19 - Major changes: Overall goals:

  • The standard component architecture for building distributed object-oriented business applications in Java.
  • Make it possible to build distributed applications by combining components developed using tools from different vendors.
  • Make it easy to write (enterprise) applications: Application developers will not have to understand low-level transaction and state management details, multi-threading, connection pooling, and other complex low-level APIs.
  • Will follow the "Write Once, Run Anywhere" philosophy of Java. An enterprise Bean can be developed once, and then deployed on multiple platforms without recompilation or source code modification.
  • Address the development, deployment, and runtime aspects of an enterprise application’s life cycle.
  • Define the contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime.
  • Be compatible with existing server platforms. Vendors will be able to extend their existing products to support EJBs.
  • Be compatible with other Java APIs.
  • Provide interoperability between enterprise Beans and Java EE components as well as non-Java programming language applications.
  • Be compatible with the CORBA protocols (RMI-IIOP).

EJB 1.1, final release (1999-12-17)

Major changes:

  • XML deployment descriptors
  • Default JNDI contexts
  • RMI over IIOP
  • Security - role driven, not method driven
  • Entity Bean support - mandatory, not optional

Goals for Release 1.1:

  • Provide better support for application assembly and deployment.
  • Specify in greater detail the responsibilities of the individual EJB roles.

EJB 1.0 (1998-03-24)

Announced at JavaOne 1998, Sun's third Java developers conference (March 24 through 27) Goals for Release 1.0:

  • Defined the distinct “EJB Roles” that are assumed by the component architecture.
  • Defined the client view of enterprise Beans.
  • Defined the enterprise Bean developer’s view.
  • Defined the responsibilities of an EJB Container provider and server provider; together these make up a system that supports the deployment and execution of enterprise Beans.

External links

References

  1. ^ J2EE Design and Development, © 2002 Wrox Press Ltd., p. 5.
  2. ^ J2EE Design and Development, © 2002 Wrox Press Ltd., p. 19.
  3. ^ http://blogs.sun.com/enterprisetechtips/entry/extended_persistence_context_in_stateful
  4. ^ http://jcp.org/en/jsr/detail?id=318