Jakarta Enterprise Beans
Jakarta Enterprise Beans is one of several Java APIs for modular construction of enterprise software. EJB is a server-side software component that encapsulates business logic of an application. An EJB web container provides a runtime environment for web related software components, including computer security, Java servlet lifecycle management, transaction processing, and other web services. The EJB specification is a subset of the Java EE specification.
SpecificationThe EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems in 1999 and enhanced under the Java Community Process as , , , and .
The EJB specification provides a standard way to implement the server-side 'business' software typically found in enterprise applications. Such software addresses the same types of problem, and solutions to these problems are often repeatedly re-implemented by programmers. Jakarta Enterprise Beans is intended to handle such common concerns as persistence, transactional integrity and security in a standard way, leaving programmers free to concentrate on the particular parts of the enterprise software at hand.
General responsibilitiesThe EJB specification details how an application server provides the following responsibilities:
- Transaction processing
- Integration with the persistence services offered by the Java Persistence API
- Concurrency control
- Event-driven programming using Java Message Service and Java EE Connector Architecture
- Asynchronous method invocation
- Job scheduling
- Naming and directory services
- Interprocess Communication using RMI-IIOP and Web services
- Deployment of software components in an application server
HistoryBusinesses found that using EJBs to encapsulate business logic brought a performance penalty. This is because the original specification allowed only for remote method invocation through CORBA, 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.
The EJB 3.0 specification was a departure from its predecessors, following a new light-weight paradigm. EJB 3.0 shows an influence from Spring in its use of plain Java objects, 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 and convention over configuration to enable a much less verbose coding style. Accordingly, in practical terms EJB 3.0 is much more lightweight and nearly a completely new API, bearing little resemblance to the previous EJB specifications.
ExampleThe following shows a basic example of what an EJB looks like in code:
public class CustomerService
The above defines a service class for persisting a Customer object. The EJB takes care of managing the persistence context and the addCustomer method is transactional and thread-safe by default. As demonstrated, the EJB focuses 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:
public class CustomerBacking
The above defines a JavaServer Faces backing bean in which the EJB is injected by means of the @EJB annotation. Its addCustomer method is typically bound to some UI component, such as 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 of Enterprise BeansAn 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 or Remote interface or directly without an interface, in which case local semantics apply. All session beans support asynchronous execution for all views.
- Message Driven Beans. MDBs also support asynchronous execution, but via a messaging paradigm.
Stateful Session BeansStateful 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. If concurrent access to a single bean is attempted anyway the container serializes those requests, but via the @AccessTimeout annotation the container can instead throw an exception. Stateful session beans' state may be persisted 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.
- 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, possibly holding locks on the items the customer is purchasing.
Stateless Session 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.
- A user of a website clicking on a "keep me informed of future updates" box may trigger a call to an asynchronous method of the session bean to add the user to a list in the company's database.
- Fetching multiple independent pieces of data for a website, like a list of products and the history of the current user might be handled by asynchronous methods of a session bean as well . In this case, the asynchronous method will return a instance.
Singleton Session Beans
- 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
- Sending a configuration update to multiple nodes might be done by sending a JMS message to a 'message topic' and could be handled by a Message Driven Bean listening to this topic.
- Submitting a job to a work cluster might be done by sending a JMS message to a 'message queue' and could also be handled by a Message Driven Bean, but this time listening to a queue.
- Processing timing events from the can be handled by a Message Driven Bean; when a Quartz trigger fires, the MDB is automatically invoked. Since Java EE doesn't know about Quartz by default, a JCA resource adapter would be needed and the MDB would be annotated with a reference to this.
Clients of EJBs do not instantiate those beans directly via Java's new operator, but instead have to obtain a reference via the EJB container. This reference is usually not a reference to the implementation bean itself, but to a proxy, which either dynamically implements the local or remote business interface that the client requested or dynamically implements a sub-type of the actual bean. The proxy can then be directly cast to the interface or bean. A client is said to have a 'view' on the EJB, and the local interface, remote interface and bean type itself respectively correspond with the local view, remote view and no-interface view.
This proxy is needed in order to give the EJB container the opportunity to transparently provide cross-cutting services to a bean like transactions, security, interceptions, injections, and remoting. As an example, a client invokes a method on a proxy, which will first start a transaction with the help of the EJB container and then call the actual bean method. When the bean method returns, the proxy ends the transaction and transfers control back to the client.
The EJB Container is responsible for ensuring the client code has sufficient access rights to an EJB. Security aspects can be declaratively applied to an EJB via annotations.
TransactionsEJB containers must support both container managed ACID transactions and bean managed transactions.
Container-managed transactions are by default active for calls to session beans. That is, no explicit configuration is needed. This behavior may be declaratively tuned by the bean via annotations and if needed such configuration can later be overridden in the deployment descriptor. Tuning includes switching off transactions for the whole bean or specific methods, or requesting alternative strategies for transaction propagation and starting or joining a transaction. Such strategies mainly deal with what should happen if a transaction is or isn't already in progress at the time the bean is called. The following variations are supported:
|MANDATORY||If the client has not started a transaction, an exception is thrown. Otherwise the client's transaction is used.|
|REQUIRED||If the client has started a transaction, it is used. Otherwise a new transaction is started.|
|REQUIRES_NEW||If the client has started a transaction, it is suspended. A new transaction is always started.|
|SUPPORTS||If the client has started a transaction, it is used. Otherwise, no transaction is used.|
|NOT_SUPPORTED||If the client has started a transaction, it is suspended. No new transaction is started.|
|NEVER||If the client has started a transaction, an exception is thrown. No new transaction is started.|
Alternatively, the bean can also declare via an annotation that it wants to handle transactions programmatically via the JTA API. This mode of operation is called Bean Managed Transactions, since the bean itself handles the transaction instead of the container.
EventsJMS is used to send messages from beans to clients, to let clients receive asynchronous messages from these beans.
MDBs can be used to receive messages from clients asynchronously using either a JMS
Queue or a Topic.
Naming and directory servicesAs an alternative to injection, clients of an EJB can obtain a reference to the session bean's proxy object using Java Naming and Directory Interface. This alternative can be used in cases where injection is not available, such as in non-managed code or standalone remote Java SE clients, or when it's necessary to programmatically determine which bean to obtain.
JNDI names for EJB session beans are assigned by the EJB container via the following scheme:
A single bean can be obtained by any name matching the above patterns, depending on the 'location' of the client. Clients in the same module as the required bean can use the module scope and larger scopes, clients in the same application as the required bean can use the app scope and higher, etc.
E.g. code running in the same module as the CustomerService bean ' could use the following code to obtain a reference to it:
CustomerServiceLocal customerService =
Remoting/distributed executionFor communication with a client that's written in the Java programming language a session bean can expose a remote-view via an @Remote annotated interface. This allows those beans to be called from clients in other JVMs which themselves may be located on other systems. From the point of view of the EJB container, any code in another JVM is remote.
Stateless- and Singleton session beans may also expose a "web service client view" for remote communication via WSDL and SOAP or plain XML. This follows the JAX-RPC and JAX-WS specifications. JAX-RPC support however is proposed for future removal. To support JAX-WS, the session bean is annotated with the @WebService annotation, and methods that are to be exposed remotely with the @WebMethod annotation..
Although the EJB specification does not mention exposure as RESTful web services in any way and has no explicit support for this form of communication, the JAX-RS specification does explicitly support EJB. Following the JAX-RS spec, Stateless- and Singleton session beans can be root resources via the @Path annotation and EJB business methods can be mapped to resource methods via the @GET, @PUT, @POST and @DELETE annotations. This however does not count as a "web service client view", which is used exclusively for JAX-WS and JAX-RPC.
Communication via web services is typical for clients not written in the Java programming language, but is also convenient for Java clients who have trouble reaching the EJB server via a firewall. Additionally, web service based communication can be used by Java clients to circumvent the arcane and ill-defined requirements for the so-called "client-libraries"; a set of jar files that a Java client must have on its class-path in order to communicate with the remote EJB server. These client-libraries potentially conflict with libraries the client may already have and such a conflict is deemed to be very hard or impossible to resolve.
Home interfaces and required business interfaceWith 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.
Required deployment descriptorWith EJB 2.1 and earlier, the EJB specification required a deployment descriptor to be present. This was needed to implement a mechanism that allowed EJBs to be deployed in a consistent manner regardless of the specific EJB platform that was chosen. Information about how the bean should be deployed had to be 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
- Java interface for the Home interface
- Java interface for the business object
- Persistent store
- Security roles and permissions
- Stateful or Stateless
Since EJB 3.0, the XML descriptor is replaced by Java annotations set in the Enterprise Bean implementation, although it is still possible to use an XML descriptor instead of 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, although some XML elements can also be additive.
Container variationsStarting with EJB 3.1, the EJB specification defines two variants of the EJB container; a full version and a limited version. The limited version adheres to a proper subset of the specification called EJB 3.1 Lite and is part of Java EE 6's web profile.
EJB 3.1 Lite excludes support for the following features:
- Remote interfaces
- RMI-IIOP Interoperability
- JAX-WS Web Service Endpoints
- EJB Timer Service
- Asynchronous session bean invocations
- Message-driven beans
- Remote interfaces
- RMI-IIOP Interoperability
- JAX-WS Web Service Endpoints
- Persistent timers
- Message-driven beans
Despite still using "EJB" the Eclipse Foundation has official renamed these as Jakarta Enterprise Beans so as not to tread on the "Java" trademark.
EJB 3.2, final release
. Enterprise JavaBeans 3.2 was a relatively minor release that mainly contained specification clarifications and lifted some restrictions that were imposed by the spec but over time appeared to serve no real purpose. A few existing full EJB features were also demanded to be in EJB 3 lite and functionality that was proposed to be pruned in EJB 3.1 was indeed pruned.
The following features were added:
- Passivation of a stateful session bean can be deactivated via attribute on @Stateful annotation
- TimerService can retrieve all active timers in the same EJB module
- Lifecycle methods can be transactional for stateful session beans using the existing @TransactionAttribute annotation
- Autocloseable interface implemented by embeddable container
. 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:
- Local view without interface
- .war packaging of EJB components
- EJB Lite: definition of a subset of EJB
- Portable EJB Global JNDI Names
- Application Initialization and Shutdown Events
- EJB Timer Service Enhancements
- 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
- Major changes:
- Web service support : 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 : Event-based mechanism for invoking EJBs at specific times.
- Message-driven beans accepts messages from sources other than JMS.
- Message destinations has been added.
- EJB query language additions: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD.
- XML schema is used to specify deployment descriptors, replaces DTDs
- Major changes:
- 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 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.
- XML deployment descriptors
- Default JNDI contexts
- RMI over IIOP
- Security - role driven, not method driven
- Entity Bean support - mandatory, not optional
- Provide better support for application assembly and deployment.
- Specify in greater detail the responsibilities of the individual EJB roles.
Announced at JavaOne 1998, Sun's third Java developers conference
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.