Jakarta Enterprise Beans
| Company type | Specification |
|---|---|
| Industry | Software, Enterprise software |
| Predecessor | Enterprise JavaBeans |
| Founded | 1997 |
| Founder | IBM |
| Parent | Jakarta EE |
Jakarta Enterprise Beans (EJB; previously known as Enterprise JavaBeans) represents a Java API designed for the modular development of enterprise software. EJB functions as a server-side software component that encapsulates the core business logic of an application. Within an EJB web container, a runtime environment is provided for web components, overseeing tasks such as computer security, the servlet lifecycle, transaction processing, and additional web services. The EJB standard forms an integral part of the larger Jakarta EE ecosystem.
Specification
The EJB specification originated in 1997 through development by IBM and was later adopted by Sun Microsystems with versions EJB 1.0 and 1.1 released in 1999. Its evolution has continued via the Java Community Process encompassing 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).
This specification standardizes server-side business components commonly utilized in enterprise applications, addressing persistent challenges such as persistence, transactional consistency, and security management. By doing so, it allows developers to concentrate on implementing specific enterprise functionalities rather than infrastructure complexities.
General responsibilities
The EJB standard outlines how an application server administers:
- Transaction processing
- Persistence integration via the Jakarta Persistence API (JPA)
- Concurrency control
- Event-driven programming through Jakarta Messaging (JMS) and Jakarta Connectors (JCA)
- Support for Asynchronous method invocation
- Scheduling of background tasks (Job scheduling)
- Naming and directory operations using the Java Naming and Directory Interface (JNDI)
- Interprocess communication facilitated by RMI-IIOP and various Web service protocols
- Security mechanisms employing the JCE and the JAAS
- Deployment procedures for components within the application server environment
Additionally, the specification details the responsibilities of both the EJB container and bean components, along with deployment workflows. While persistence is managed by JPA implementations, EJB defines how business logic interacts effectively with these persistence layers.
History
Initially, enterprises encountered performance drawbacks when utilizing EJBs to encapsulate business rules because the original design restricted method calls to remote invocations via CORBA, even though many business applications did not require distributed processing. To resolve this, EJB 2.0 introduced local interfaces allowing direct method calls that avoid the overhead associated with remote communication in non-distributed contexts.
With EJB 3.0 (JSR 220), there was a transition toward a more lightweight model inspired by frameworks like Spring. This version embraced plain Java objects alongside support for dependency injection, reducing configuration complexity and enhancing integration capabilities. It also offers compatibility with MuleSoft-v4 through the MuleSoft-certified PlektonLabs EJB Connector. Gavin King, known for creating Hibernate, played a significant role in shaping EJB 3.0 and endorsed its design; numerous Hibernate features were incorporated into the Java Persistence API, effectively replacing traditional entity beans. The approach in EJB 3.0 heavily relies on annotations and embraces a principle of convention over configuration, resulting in a much leaner API that represents a substantial redesign compared to earlier iterations.
Example
A straightforward illustration of an EJB:
<syntaxhighlight lang=java> @Stateless public class CustomerService {
private EntityManager entityManager;
public void addCustomer(Customer customer) {
entityManager.persist(customer);
}
} </syntaxhighlight>
This service class is responsible for persisting a Customer entity through O/R mapping. The EJB manages the persistence context, with the addCustomer() method inherently transactional and safe for concurrent use. Its role is confined to business logic and data persistence, without any dependency on the presentation layer.
Demonstration of usage within a web layer component:
<syntaxhighlight lang="java"> @Named @RequestScoped public class CustomerBacking {
@EJB private CustomerService customerService;
public String addCustomer(Customer customer) {
customerService.addCustomer(customer);
context.addMessage(...); // abbreviated
return "customer_overview";
}
} </syntaxhighlight>
In this example, a JavaServer Faces (JSF) backing bean obtains the EJB via @EJB injection. The addCustomer method is generally linked to UI elements such as buttons. Unlike the EJB, this backing bean does not implement business or persistence logic but delegates these responsibilities, while it remains aware of presentation concerns that the EJB disregards.
Types of Enterprise Beans
An EJB container oversees two primary categories of beans:
- Session Beans, which may be "Stateful," "Stateless," or "Singleton," accessible through Local (within the same JVM), Remote (across JVMs) interfaces, or directly without an interface applying local semantics. Asynchronous execution is supported by all session beans.
- Message Driven Beans (MDBs), which also facilitate asynchronous processing via messaging.
Stateful Session Beans
Stateful Session Beans preserve client-specific state across a session and are dedicated to a single client instance. Concurrent access is serialized or can cause exceptions controlled by the @AccessTimeout annotation. To optimize memory usage, containers may passivate these beans after periods of inactivity. They explicitly support the JPA extended persistence context.
- Examples
- Coordinating a web store checkout by maintaining customer progress and locking items during purchase, simplifying client-side handling.
Stateless Session Beans
Stateless Session Beans do not hold any client state and prevent concurrent access to individual instances; instead, the container dispatches requests among multiple instances to ensure thread safety. These beans are typically pooled and reused across different clients, making them more resource-efficient than their stateful counterparts.
- Examples
- Executing single operations such as sending emails for customer support.
- Adding users asynchronously to mailing lists triggered by website events.
- Concurrently retrieving distinct datasets (like product catalogs and user histories) via asynchronous methods returning Future objects, enhancing throughput.
Singleton Session Beans
Singleton Session Beans represent business components with shared state across the entire JVM. Access concurrency to this sole instance is managed either by the container (Container-managed concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC). Container-managed concurrency is configured with the @Lock annotation to specify read or write locks on methods. Additionally, Singleton Beans can be initialized when the container starts using the @Startup annotation.
- Examples
- Loading a universal daily price list accessible by all users, minimizing repeated database queries.
Message driven beans
Message Driven Beans represent business components activated by incoming messages instead of direct method invocations. They serve as an abstraction layer over JMS (Java Message Service), connecting to JMS queues or topics through the @MessageDriven annotation's activationConfig parameter. Designed to facilitate event-based processing, MDBs operate without a client interface and autonomously handle received messages. Although Java EE mandates JMS support, MDBs are capable of processing various messaging protocols, both synchronous and asynchronous. Their primary difference from session beans lies in responding to messages rather than method calls.
- Use cases
- Broadcasting configuration changes via JMS topics to multiple nodes without the sender needing awareness of the recipients.
- Dispatching tasks to a work cluster through JMS queues, ensuring each task is executed exactly once.
- Managing scheduled events from the Quartz scheduler by utilizing a JCA resource adapter in combination with MDB annotations.
Execution
EJBs are deployed within an EJB container, commonly part of an application server. The specification outlines the interactions among an EJB, its container, and client applications. Application EJB classes are placed in the package, whereas is reserved exclusively for EJB container implementations.
Clients do not create EJB instances directly; instead, they acquire references through the container. These references typically take the form of proxies implementing the targeted local or remote business interface or a bean subtype. Consequently, clients interact with an EJB 'view' that may be local, remote, or no-interface.
These proxies allow the container to seamlessly provide cross-cutting concerns such as transaction handling, security enforcement, interception mechanisms, dependency injection, and remote communication. For instance, invoking a proxy method prompts the container to manage transactions before and after executing the bean's method.
The EJB container enforces appropriate access permissions for clients interacting with EJBs. Security configurations can be applied declaratively using annotations.
Transactions
EJB containers accommodate both container-managed transactions (CMT) and bean-managed transactions (BMT).
By default, session bean invocations are governed by container-managed transactions unless explicitly overridden. Beans can customize this behavior through annotations or deployment descriptors, including disabling transaction support or defining transaction propagation policies. These policies determine how transactions behave when a bean method is invoked with or without an active client transaction:
| Policy | Description |
|---|---|
| MANDATORY | Requires an existing client transaction; otherwise throws an exception. |
| REQUIRED | Joins client's transaction if available; starts a new one if not (default). |
| REQUIRES_NEW | Suspends any current client transaction and initiates a new one. |
| SUPPORTS | Participates in client's transaction if present; otherwise executes without a transaction. |
| NOT_SUPPORTED | Suspends any client transaction; does not create a new transaction. |
| NEVER | Throws an exception if a client transaction exists; does not start a new one. |
Alternatively, beans may opt for programmatic control over transactions using the JTA, referred to as Bean Managed Transactions (BMT), where transaction boundaries are explicitly handled by the bean rather than the container.
Events
JMS (Java Message Service) facilitates asynchronous communication between beans and clients. Message-Driven Beans (MDBs) handle asynchronous messages delivered through JMS Queues or Topics.
Naming and directory services
EJB session bean references can be acquired by clients either through injection or by using the Java Naming and Directory Interface (JNDI), particularly useful in unmanaged environments or standalone Java SE applications. The EJB container assigns JNDI names according to the following format:
| Scope | Naming pattern |
|---|---|
| Global | java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>] |
| Application | java:app/<module-name>/<bean-name>[!<fully-qualified-interface-name>] |
| Module | java:module/<bean-name>[!<fully-qualified-interface-name>] |
Clients select bean references depending on their deployment context—clients within the same module use the module scope, those within the same application use app scope, and so forth. For instance, code residing in the same module as the CustomerService bean can retrieve a local reference as shown below:
<syntaxhighlight lang=java> CustomerServiceLocal customerService =
(CustomerServiceLocal) new InitialContext().lookup("java:module/CustomerService");
</syntaxhighlight>
Remoting/distributed execution
Remote interfaces annotated with @Remote allow session beans to be accessed by Java clients running in different JVMs, supporting distributed processing. Additionally, Stateless and Singleton beans may expose "web service client views" through WSDL and SOAP, adhering to JAX-RPC and JAX-WS specifications; however, JAX-RPC support is planned for deprecation. These services are made available using @WebService and @WebMethod annotations.
Although EJB specifications do not explicitly provide RESTful service support, the JAX-RS standard enables Stateless and Singleton beans to function as RESTful resources by employing annotations such as @Path, @GET, @PUT, @POST, and @DELETE. This REST integration offers modern web service capabilities distinct from traditional "web service client views."
Web service interfaces are particularly advantageous for non-Java clients or Java clients hindered by firewall constraints or conflicts with required client libraries. Since remote EJB communication depends on specific client libraries that may interfere with existing dependencies in complex Java setups, web services present a viable alternative.
Home interfaces and required business interface
Prior to EJB 3.0, specifically in EJB 2.1 and earlier versions, each EJB implementation involved a Java class along with two interfaces. The container was responsible for creating instances of the implementation class, while clients interacted exclusively via these interfaces.
Required deployment descriptor
Before EJB 3.0, deployment descriptors were mandatory to ensure consistent deployment across different platforms. This XML file detailed configuration elements such as:
- Names of home interfaces
- Bean implementation class
- Home and business interfaces
- Persistent storage details (for Entity Beans)
- Security roles and authorization settings
- Whether session beans were stateful or stateless
Many vendors also required supplementary deployment details through additional XML files or configuration resources. Vendor-specific tools typically processed these descriptors to generate classes that implemented the now-obsolete Home and Remote interfaces.
From EJB 3.0 onward, Java annotations embedded within bean classes have largely replaced XML deployment descriptors, although XML files may still be used to override or complement annotation-based configurations during deployment.
Container editions
Beginning with EJB 3.1, there are two types of containers available: the full version and a limited edition known as EJB 3.1 Lite, which is incorporated into the Java EE 6 web profile. The EJB 3.1 Lite variant does not support:
- Remote interfaces
- RMI-IIOP interoperability
- JAX-WS Web Service Endpoints
- The EJB Timer Service (annotations such as @Schedule and @Timeout)
- Asynchronous invocation of session beans (@Asynchronous)
- Message-driven beans
With EJB 3.2 Lite, certain capabilities like @Asynchronous and @Schedule/@Timeout (excluding persistent timers) are reinstated, yet it continues to exclude:
- Remote interfaces
- RMI-IIOP interoperability
- JAX-WS Web Service Endpoints
- Persistent timers (the "persistent" attribute on @Schedule)
- Message-driven beans
Release timeline
EJB 4.0, official release (2020-05-22)
Part of Jakarta EE 9, the Jakarta Enterprise Beans 4.0 specification primarily involved transitioning API package names from to . It also eliminated deprecated APIs and features dependent on components removed in Java or Jakarta EE 9, including:
- Methods utilizing (removed in Java 14)
- Methods dependent on Jakarta XML RPC (removed in Jakarta EE 9)
- Deprecated method
- Features related to "Support for Distributed Interoperability" due to CORBA removal from Java 11 and Jakarta EE 9
Other modifications included designating the Enterprise Beans 2.x API Group as "Optional" and allowing the annotation to be repeatable.
EJB 3.2.6, official release (2019-08-23)
As part of Jakarta EE 8, Jakarta Enterprise Beans 3.2 marked the formal rebranding by the Eclipse Foundation from Oracle's "Java" trademark to "Jakarta Enterprise Beans," while retaining the "EJB" acronym.
EJB 3.2, official release (2013-05-28)
(JSR 345) This minor revision addressed specification clarifications and lifted unnecessary constraints. Notable improvements included:
- Ability to disable passivation for stateful session beans via
@Stateful(passivationCapable = false) - TimerService capability to access all active timers within the same EJB module
- Support for transactional lifecycle methods (e.g.,
@PostConstruct) in stateful session beans using@TransactionAttribute - Embeddable container implementing the Autocloseable interface
EJB 3.1, official release (2009-12-10)
(JSR 318) Introduced a streamlined EJB model with features such as:
- No-interface local view
- Packaging EJB components inside .war files
- Definition of an EJB Lite subset
- Portable global JNDI naming conventions
- Singleton Session Beans
- Application lifecycle event notifications for initialization and shutdown
- Enhanced EJB Timer Service capabilities
- Simplified asynchronous processing using
@Asynchronous
EJB 3.0, official release (2006-05-11)
(JSR 220) Significantly simplified development by replacing complex deployment descriptors with annotations; removed home and remote interfaces in favor of business interfaces directly implemented by beans.
EJB 2.1, official release (2003-11-24)
(JSR 153) Added web service support enabling stateless session beans to be accessed via SOAP/HTTP, introduced an EJB timer service for event-driven invocation, enhanced message-driven beans to process non-JMS messages, incorporated message destinations, extended the EJB query language with aggregate functions, and transitioned deployment descriptors from DTDs to XML schemas.
EJB 2.0, official release (2001-08-22)
(JSR 19) Established a standardized component framework for distributed object-oriented business applications in Java that supports interoperability among tools from multiple vendors; simplified enterprise application development by abstracting complexities such as transaction management and threading; adhered to Java’s "Write Once, Run Anywhere" principle; addressed full application lifecycle management; ensured compatibility with existing servers and Java APIs; facilitated integration with both Java EE components and non-Java applications; and supported CORBA protocols through RMI-IIOP.
EJB 1.1, official release (1999-12-17)
Introduced XML-based deployment descriptors, default JNDI contexts, RMI over IIOP communication, a role-based security model, and mandatory support for entity beans. Also improved application assembly and deployment processes while clarifying responsibilities for each EJB role.
EJB 1.0 (1998-03-24)
Announced at JavaOne 1998, this initial release defined fundamental EJB roles within the component architecture encompassing client views, developer perspectives, and container/server provider duties essential for deploying and running enterprise Beans.
External links
- Jakarta Enterprise Beans Specification
- EJB 3.0 API Documentation
- The EJB 3.0 Specification
- Sun's EJB 3.0 Tutorial
- Glossary for EJB (3.0)
- Frequently Asked Questions about EJB
- JSR 345 (EJB 3.2)
- JSR 318 (EJB 3.1)
- JSR 220 (EJB 3.0)
- JSR 153 (EJB 2.1)
- JSR 19 (EJB 2.0)
- "Working with Message-Driven Beans" from EJB3 in Action, Second Edition
- Client Interaction with an EJB