Jakarta Enterprise Beans (EJB; formerly Enterprise JavaBeans) 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 Jakarta EE specification.
Specification The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999J2EE Design and Development, 2002 Wrox Press Ltd., p. 5. and enhanced under the Java Community Process as JSR 19 (EJB 2.0), JSR 153 (EJB 2.1), JSR 220 (EJB 3.0), JSR 318 (EJB 3.1) and JSR 345 (EJB 3.2).
The EJB specification provides a standard way to implement the server-side (also called "back-end") 'business' software typically found in enterprise applications (as opposed to 'front-end' user interface software). 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 responsibilities The EJB specification details how an application server provides the following responsibilities: Transaction processing Integration with the persistence services offered by the Jakarta Persistence (JPA) Concurrency control Event-driven programming using Jakarta Messaging (JMS) and Jakarta Connectors (JCA) Asynchronous method invocation Job scheduling Naming and directory services via Java Naming and Directory Interface (JNDI) Interprocess Communication using RMI-IIOP and Web services Security (JCE and JAAS) Deployment of software components in an application server
Additionally, the Jakarta Enterprise Beans specification defines the roles played by the EJB container and the EJBs as well as how to deploy the EJBs in a container. Note that the EJB specification does not detail how an application server provides persistence (a task delegated to the JPA specification), but instead details how business logic can easily integrate with the persistence services offered by the application server.
History Businesses 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 (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.J2EE Design and Development, 2002, Wrox Press Ltd., p. 19.
The EJB 3.0 specification (JSR 220) 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. EJB 3.0 along with the other version of the EJB can be integrated with MuleSoft-v4 using MuleSoft certified PlektonLabs EJB Connector. 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) 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.
Example The following shows a basic example of what an EJB looks like in code:
@Stateless public class CustomerService {
private EntityManager entityManager;
public void addCustomer(Customer customer) { entityManager.persist(customer);
The above defines 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 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:
@Named @RequestScoped public class CustomerBacking { @EJB private CustomerService customerService;
public String addCustomer(Customer customer) { customerService.addCustomer(customer); context.addMessage(...); // abbreviated for brevity return "customer_overview";
The above defines a JavaServer Faces (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, 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 Beans An EJB container holds two major types of beans: Session BeansJSR 318, 4.1, http://jcp.org/en/jsr/detail?id=318 that can be either "Stateful", "Stateless" or "Singleton" and can be accessed via either a Local (same JVM) or Remote (different JVM) interface or directly without an interface, in which case local semantics apply. All session beans support asynchronous executionJSR 318, 4.5, http://jcp.org/en/jsr/detail?id=318 for all views (local/remote/no-interface). Message Driven Beans (MDBs, also known as Message Beans). MDBs also support asynchronous execution, but via a messaging paradigm.
Session beans
Stateful Session Beans
Stateful Session BeansJSR 318, 4.6, http://jcp.org/en/jsr/detail?id=318 are business objects having state: that is, they keep track of which calling client they are dealing with throughout a session and of the history of its requests, and thus access to the bean instance is strictly limited to only one client during its lifetime.JSR 318, 4.10.3, http://jcp.org/en/jsr/detail?id=318 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.JSR 318, 4.3.14, 21.4.2, http://jcp.org/en/jsr/detail?id=318 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. Examples 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 (from a system architecture's point of view, it would be less ideal to have the client manage those locks).
Stateless Session Beans Stateless Session BeansJSR 318, 4.7, http://jcp.org/en/jsr/detail?id=318 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, concurrent access to the bean is prohibited. If concurrent access to a single bean is attempted, the container simply routes each request to a different instance.JSR 318, 4.3.14, http://jcp.org/en/jsr/detail?id=318 This makes a stateless session bean automatically thread-safe. Instance variables can be used during a single method call from a client to the bean, but the contents of those instance variables are not guaranteed to be preserved across different client 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. Examples 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 (this call is asynchronous because the user does not need to wait to be informed of its success or failure). 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 (these calls are asynchronous because they can execute in parallel that way, which potentially increases performance). In this case, the asynchronous method will return a Future instance.
Singleton Session Beans Singleton Session BeansJSR 318, 4.8, http://jcp.org/en/jsr/detail?id=318 are business objects having a global shared state within a JVM. 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. Examples 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 Message Driven BeansJSR 318, 5.1, http://jcp.org/en/jsr/detail?id=318 are business objects whose execution is triggered by messages instead of by method calls. The Message Driven Bean is used among others to provide a high level ease-of-use abstraction for the lower level JMS (Java Message Service) specification. It may subscribe to JMS message queues or message topics, which typically happens via the activationConfig attribute of the @MessageDriven annotation. They were added in EJB to allow event-driven processing. Unlike session beans, an MDB does not have a client view (Local/Remote/No-interface), i. e. clients cannot look-up an MDB instance. An MDB just listens for any incoming message on, for example, a JMS queue or topic and processes them automatically. Only JMS support is required by the Java EE spec,JSR 318, 5.7.2, http://jcp.org/en/jsr/detail?id=318 but Message Driven Beans can support other messaging protocols.JSR 318, 5.4.2, http://jcp.org/en/jsr/detail?id=318JSR 318, 5.6.2, http://jcp.org/en/jsr/detail?id=318 Such protocols may be asynchronous but can also be synchronous. Since session beans can also be synchronous or asynchronous, the prime difference between session- and message driven beans is not the synchronicity, but the difference between (object oriented) method calling and messaging. Examples 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 (the message paradigm is used here since the sender does not need to know the number of consumers, their location, or even their exact type).