Specification: Jakarta® Enterprise Beans, Core Features Version: 4.0 Status: Final Release: November 05, 2020
Copyright
Copyright © 2018, 2020 Eclipse Foundation. https://www.eclipse.org/legal/efsl.php
Eclipse Foundation Specification License
By using and/or copying this document, or the Eclipse Foundation document from which this statement is linked, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions:
Permission to copy, and distribute the contents of this document, or the Eclipse Foundation document from which this statement is linked, in any medium for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the document, or portions thereof, that you use:
-
link or URL to the original Eclipse Foundation document.
-
All existing copyright notices, or if one does not exist, a notice (hypertext is preferred, but a textual representation is permitted) of the form: "Copyright © [$date-of-document] Eclipse Foundation, Inc. <<url to this license>>"
Inclusion of the full text of this NOTICE must be provided. We request that authorship attribution be provided in any software, documents, or other items or products that you create pursuant to the implementation of the contents of this document, or any portion thereof.
No right to create modifications or derivatives of Eclipse Foundation documents is granted pursuant to this license, except anyone may prepare and distribute derivative works and portions of this document in software that implements the specification, in supporting materials accompanying such software, and in documentation of such software, PROVIDED that all such works include the notice below. HOWEVER, the publication of derivative works of this document for use as a technical specification is expressly prohibited.
The notice is:
"Copyright © [$date-of-document] Eclipse Foundation. This software or document includes material copied from or derived from [title and URI of the Eclipse Foundation specification document]."
Disclaimers
THIS DOCUMENT IS PROVIDED "AS IS," AND THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.
The name and trademarks of the copyright holders or the Eclipse Foundation may NOT be used in advertising or publicity pertaining to this document or its contents without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.
1. Introduction
This is the specification of the Jakarta® Enterprise Beans architecture. The Enterprise Beans architecture is an architecture for the development and deployment of component-based business applications. Applications written using the Enterprise Beans architecture are scalable, transactional, and multi-user secure. These applications may be written once, and then deployed on any server platform that supports the Enterprise Beans specification.
1.1. Target Audience
The target audiences for this specification are the vendors of transaction processing platforms, vendors of enterprise application tools, and other vendors who want to support the Enterprise Beans technology in their products.
Many concepts described in this document are system-level issues that are transparent to the Enterprise Beans application programmer.
1.2. What is New in This Release
The Enterprise Beans 4.0 specification is a breaking change from
prior Enterprise Beans specifications delivering a namespace change
from javax
to jakarta
across the API along with removal of
deprecated APIs.
-
All
javax.ejb
namespace/packages have been renamed tojakarta.ejb
. -
Removed the methods relying on
java.security.Identity
which has been removed from the Java 14. -
Removed the methods relying on Jakarta XML RPC to reflect the removal of XML RPC from the Jakarta EE 9 Platform.
-
Removed the deprecated
EJBContext.getEnvironment()
method. -
Removed the “Support for Distributed Interoperability” to reflect the removal of CORBA from Java 11 and the Jakarta EE 9 Platform.
-
Marked the Enterprise Beans 2.x API Group as “Optional”.
-
@Schedule
annotation is now repeatable.
1.3. What was New in Jakarta Enterprise Beans 3.2
The Jakarta Enterprise Beans 3.2 [27] architecture is the first official release from the Eclipse Foundation under the specification’s new name of “Jakarta Enterprise Beans” after the successful donation of Enterprise JavaBeans by Oracle.
The Jakarta Enterprise Beans 3.2 release is identical to Enterprise JavaBeans 3.2 and only differs by name and license.
1.4. What was New in Enterprise JavaBeans 3.2
The Enterprise JavaBeans 3.2 [1] architecture extends Enterprise JavaBeans to include the following new functionality and simplifications to the earlier Enterprise JavaBeans APIs:
-
Made support for the following features optional in this release and moved their description to a separate Enterprise JavaBeans Optional Features [2] document:
-
Enterprise JavaBeans 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence
-
Enterprise JavaBeans 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence
-
Client View of an Enterprise JavaBeans 2.1 and earlier Entity Bean
-
Enterprise JavaBeans QL: Query Language for Container-Managed Persistence Query Methods
-
Jakarta XML RPC Based Web Service Endpoints
-
Jakarta XML RPC Web Service Client View
-
-
Enhanced message-driven beans contract with a no-methods message listener interface to expose all public methods as message listener methods.
-
Defined the Enterprise JavaBeans API Groups with clear rules for an Enterprise JavaBeans Lite Container to support other API groups.
-
Added container provided security role named “
**
” to indicate any authenticated caller independent of the actual role name. -
Extended the Enterprise JavaBeans Lite Group to include local asynchronous session bean invocations and non-persistent Enterprise JavaBeans Timer Service.
-
Added an option for the lifecycle callback interceptor methods of stateful session beans to be executed in a transaction context determined by the lifecycle callback method’s transaction attribute.
-
Introduced an option to disable passivation of stateful session beans.
-
Enhanced the TimerService API to access all active timers in the Enterprise JavaBeans module.
-
Enhanced the embeddable EJBContainer to implement
AutoCloseable
interface. -
Removed restrictions on
jakarta.ejb.Timer
andjakarta.ejb.TimerHandle
that required references to be used only inside a bean. -
Relaxed default rules for a session bean to designate its implemented interfaces as local or as remote business interfaces.
-
Enhanced the list of standard Jakarta® Messaging MDB activation properties.
-
Simplified requirements for definition of a security role using the ejb deployment descriptor.
-
Removed restriction on obtaining the current class loader; replaced ‘must not’ with ‘should exercise caution’ when using the Java I/O package.
1.5. What was New in Enterprise JavaBeans 3.1
The Enterprise JavaBeans 3.1 [28] architecture extended Enterprise JavaBeans to include the following new functionality and simplifications to the earlier Enterprise JavaBeans APIs:
-
A simplified local view that provides session bean access without a separate local business interface.
-
Packaging and deployment of Enterprise JavaBeans components directly in a
.war
file without an ejb-jar file. -
An embeddable API for executing Enterprise JavaBeans components within a Java SE environment.
-
A singleton session bean component that provides easy access to shared state as well as application startup and shutdown callbacks.
-
Automatically created Enterprise JavaBeans Timers.
-
Calendar-based Enterprise JavaBeans Timer expressions.
-
Asynchronous session bean invocations.
-
The definition of a lightweight subset of Enterprise JavaBeans functionality that is provided within the Jakarta® EE Web Profile.
-
A portable global JNDI name syntax for looking up Enterprise JavaBeans components.
1.5.1. What was New in Enterprise JavaBeans 3.0
The Enterprise JavaBeans 3.0 [29] architecture extended Enterprise JavaBeans to include the following new functionality and simplifications to the earlier Enterprise JavaBeans APIs:
-
Definition of the Java language metadata annotations that can be used to annotate Enterprise JavaBeans applications. These metadata annotations are targeted at simplifying the developer’s task, at reducing the number of program classes and interfaces the developer is required to implement, and at eliminating the need for the developer to provide an Enterprise JavaBeans deployment descriptor.
-
Specification of programmatic defaults, including for metadata, to reduce the need for the developer to specify common, expected behaviors and requirements on the Enterprise JavaBeans container. A "configuration by exception" approach is taken whenever possible.
-
Encapsulation of environmental dependencies and JNDI access through the use of annotations, dependency injection mechanisms, and simple lookup mechanisms.
-
Simplification of the enterprise bean types.
-
Elimination of the requirement for Enterprise JavaBeans component interfaces for session beans. The required business interface for a session bean can be a plain Java interface rather than an
EJBObject
,EJBLocalObject
, orjava.rmi.Remote
interface. -
Elimination of the requirement for home interfaces for session beans.
-
Simplification of entity persistence through the Jakarta® Persistence [3]. Support for light-weight domain modeling, including inheritance and polymorphism.
-
Specification of Java language metadata annotations and XML deployment descriptor elements for the object/relational mapping of persistent entities [3].
-
A query language for Jakarta Persistence that is an extension to Enterprise JavaBeans QL, with addition of projection, explicit inner and outer join operations, bulk update and delete, subqueries, and group-by. Addition of a dynamic query capability and support for native SQL queries.
-
An interceptor facility for session beans and message-driven beans.
-
Reduction of the requirements for usage of checked exceptions.
-
Elimination of the requirement for the implementation of callback interfaces.
1.6. Acknowledgements
The Enterprise Beans 4.0 specification work was done under the Jakarta EE Specification Process (JESP).
1.7. Acknowledgements for Enterprise JavaBeans 3.2
The Enterprise JavaBeans 3.2 specification work was conducted as part of JSR-345 under the Java Community Process Program. This specification is the result of the collaborative work of the members of the Enterprise JavaBeans 3.2 Expert Group: Caucho Technology, Inc: Reza Rahman; IBM: Jeremy Bauer; Oracle: Marina Vatkina, Linda DeMichiel; OW2: Florent Benoit; Pramati Technologies: Ravikiran Noothi; RedHat: Pete Muir, Carlo de Wolf; TmaxSoft, Inc.: Miju Byon; individual members: Adam Bien; David Blevins; Antonio Goncalves; Stefan Heldt; Richard Hightower, Jean-Louis Monteiro.
1.8. Organization of the Specification Documents
This specification is organized into the following documents:
-
Enterprise Beans Core Features
-
Enterprise Beans Optional Features
This Enterprise Beans Core Features document defines the contracts and requirements for the use and implementation of Enterprise Beans. These contracts include those for the Enterprise Beans 4.0 API, as well as for the earlier Enterprise Beans API that is required to be supported in this release. See Runtime Environment for coverage of the Enterprise Beans API requirements.
The Enterprise Beans Optional Features document [2] defines the contracts and requirements for the use and implementation of features support for which has been made optional as of Enterprise JavaBeans, 3.2. These contracts are separated from the core contracts requirements of the Enterprise JavaBeans 3.1 specification.
1.9. Document Conventions
The regular font is used for information that is prescriptive by the Enterprise Beans specification.
The italic font is used for paragraphs that contain descriptive information, such as notes describing typical use, or notes clarifying the text with prescriptive specification.
The monospace font is used for code examples.
2. Overview
2.1. Overall Goals
The Enterprise Beans architecture has the following goals:
-
The Enterprise Beans architecture will be the standard component architecture for building object-oriented business applications in the Java™ programming language.
-
The Enterprise Beans architecture will support the development, deployment, and use of distributed business applications in the Java™ programming language.
-
The Enterprise Beans architecture will support the development, deployment, and use of web services.
-
The Enterprise Beans architecture will make it easy to write applications: application developers will not have to understand low-level transaction and state management details, multi-threading, connection pooling, or other complex low-level APIs.
-
Enterprise Beans applications will follow the Write Once, Run Anywhere™ philosophy of the Java programming language. An enterprise bean can be developed once, and then deployed on multiple platforms without recompilation or source code modification.
-
The Enterprise Beans architecture will address the development, deployment, and runtime aspects of an enterprise application’s life cycle.
-
The Enterprise Beans architecture will define the contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime.
-
The Enterprise Beans architecture will make it possible to build applications by combining components developed using tools from different vendors.
-
The Enterprise Beans architecture will provide interoperability between enterprise beans and Jakarta EE components as well as non-Java programming language applications.
-
The Enterprise Beans architecture will be compatible with existing server platforms. Vendors will be able to extend their existing products to support Enterprise Beans.
-
The Enterprise Beans architecture will be compatible with other Java programming language APIs.
-
The Enterprise Beans architecture will be compatible with the CORBA protocols.
The purpose of the Enterprise Beans 4.0 release is both to continue to achieve these goals and to improve the Enterprise Beans architecture by reducing its complexity from the enterprise application developer’s point of view.
2.2. Enterprise Beans Roles
The Enterprise Beans architecture defines six distinct roles in the application development and deployment life cycle. Each Enterprise Beans role may be performed by a different party. The Enterprise Beans architecture specifies the contracts that ensure that the product of each Enterprise Beans role is compatible with the product of the other Enterprise Beans roles. The Enterprise Beans specification focuses on those contracts that are required to support the development and deployment of enterprise beans.
The following sections define the six Enterprise Beans roles.[1]
2.2.1. Enterprise Bean Provider
The Enterprise
Bean Provider (Bean Provider for short) is the producer of enterprise
beans. His or her output is a set of one or more enterprise beans. These
beans may be contained in a ejb-jar
or may be contained directly in a .war
file.
The Bean Provider is responsible for the Java classes that implement the
enterprise beans’ business methods; the definition of the beans’ client
view interfaces, if any; and the declarative specification of the beans’
metadata. The beans’ metadata may take the form of metadata annotations
applied to the bean classes and/or an external XML deployment
descriptor. The beans’ metadata—whether expressed in metadata
annotations or in the deployment descriptor—includes the structural
information of the enterprise beans and declares all the enterprise
beans’ external dependencies (e.g. the names and types of resources that
the enterprise beans use).
The Enterprise Bean Provider is typically an application domain expert. The Bean Provider develops reusable enterprise beans that typically implement business tasks or business entities.
The Bean Provider is not required to be an expert at system-level programming. Therefore, the Bean Provider usually does not program transactions, concurrency, security, distribution, or other services into the enterprise beans. The Bean Provider relies on the container for these services.
A Bean Provider of multiple enterprise beans often performs the role of the Application Assembler.
2.2.2. Application Assembler
The Application
Assembler combines enterprise beans into larger deployable application
units. The input to the Application Assembler is a set of enterprise
beans, their interfaces, and metadata, as produced by the Bean
Provider(s). The Bean Provider’s output may also simply be un-assembled
enterprise beans that must be packaged in an ejb-jar file or .war
file. The Application Assembler may insert the application assembly
instructions into the deployment descriptors. The Application Assembler
will create one or more ejb-jar and/or .war
files from the input
artifacts together with their application assembly instructions as
needed.
All of the input could be combined into a
single output ejb-jar file or .war
file. Similarly, the input could
also be split into multiple output ejb-jar and/or .war
files. For
example, the Application Assembler could combine ejb1.jar and ejb2.jar
into ejb3.jar, combine ejb1.jar and web1.war into web2.war, split
ejb1.jar into ejb2.jar and ejb3.jar, split web1.war into ejb1.jar and
web2.jar, and so forth. Each output ejb-jar file or .war
file is
either a deployment unit intended for the Deployer or a partially
assembled application that is intended for another Application
Assembler.
The Application Assembler can also combine enterprise beans with other types of application components when composing an application.
The Enterprise Beans specification describes the case in which the application assembly step occurs before the deployment of the enterprise beans. However, the Enterprise Beans architecture does not preclude the case that application assembly is performed after the deployment of all or some of the enterprise beans.
The Application Assembler is a domain expert who composes applications that use enterprise beans. The Application Assembler works with the enterprise beans’ metadata annotations and/or deployment descriptor and the enterprise beans’ client-view contract. Although the Assembler must be familiar with the functionality provided by the enterprise beans’ client-view, he or she does not need to have any knowledge of the enterprise beans’ implementation.
2.2.3. Deployer
The Deployer takes one or more ejb-jar files and/or .war file produced by a Bean Provider or Application Assembler and deploys the enterprise beans contained in the ejb-jar files or .war files in a specific operational environment. The operational environment includes an Enterprise Beans container and server.
The Deployer must resolve all the external dependencies declared by the Bean Provider (e.g. the Deployer must ensure that all resource manager connection factories used by the enterprise beans are present in the operational environment, and he or she must bind them to the resource manager connection factory references declared in the metadata annotations or deployment descriptor), and must follow the application assembly instructions defined by the Application Assembler. To perform his or her role, the Deployer uses tools provided by the Container Provider.
The Deployer’s output is a set of enterprise beans (or an assembled application that includes enterprise beans) that have been customized for the target operational environment, and that are deployed in a specific Enterprise Beans container.
The Deployer is an expert at a specific operational environment and is responsible for the deployment of enterprise beans. For example, the Deployer is responsible for mapping the security roles defined by the Bean Provider or Application Assembler to the user groups and accounts that exist in the operational environment in which the enterprise beans are deployed.
The Deployer uses tools supplied by the Container Provider to perform the deployment tasks. The deployment process is typically two-stage:
-
The Deployer first generates the additional classes and interfaces that enable the container to manage the enterprise beans at runtime. These classes are container-specific.
-
The Deployer performs the actual installation of the enterprise beans and the additional classes and interfaces into the Enterprise Beans container.
In some cases, a qualified Deployer may customize the business logic of the enterprise beans at their deployment. Such a Deployer would typically use the Container Provider’s tools to write relatively simple application code that wraps the enterprise beans’ business methods.
2.2.4. Enterprise Beans Server Provider
The Enterprise Beans Server Provider (Server Provider for short) is a specialist in the area of distributed transaction management, distributed objects, and other lower-level system-level services.
The current Enterprise Beans architecture assumes that the Server Provider and the Container Provider roles are the same vendor. Therefore, it does not define any interface requirements for the Server Provider.
2.2.5. Enterprise Beans Container Provider
The Enterprise Beans Container Provider (Container Provider for short) provides:
-
The deployment tools necessary for the deployment of enterprise beans.
-
The runtime support for the deployed enterprise bean instances.
From the perspective of the enterprise beans, the container is a part of the target operational environment. The container runtime provides the deployed enterprise beans with transaction and security management, network distribution of remote clients, scalable management of resources, and other services that are generally required as part of a manageable server platform.
The "Enterprise Beans Container Provider’s responsibilities" defined by the Enterprise Beans architecture are meant to be requirements for the implementation of the Enterprise Beans container and server. Since the Enterprise Beans specification does not architect the interface between the Enterprise Beans container and server, it is left up to the vendor how to split the implementation of the required functionality between the Enterprise Beans container and server.
The expertise of the Container Provider is system-level programming, possibly combined with some application-domain expertise. The focus of a Container Provider is on the development of a scalable, secure, transaction-enabled container that is integrated with an Enterprise Beans server. The Container Provider insulates the enterprise bean from the specifics of an underlying Enterprise Beans server by providing a simple, standard API between the enterprise bean and the container. This API is the Enterprise Beans component contract.
The Container Provider typically provides support for versioning the installed enterprise bean components. For example, the Container Provider may allow enterprise bean classes to be upgraded without invalidating existing clients or losing existing enterprise bean objects.
The Container Provider typically provides tools that allow the System Administrator to monitor and manage the container and the beans running in the container at runtime.
2.2.6. System Administrator
The System Administrator is responsible for the configuration and administration of the enterprise’s computing and networking infrastructure that includes the Enterprise Beans server and container. The System Administrator is also responsible for overseeing the well-being of the deployed enterprise beans applications at runtime.
2.3. Enterprise Beans
Enterprise Beans is an architecture for component-based transaction-oriented enterprise applications.
2.3.1. Characteristics of Enterprise Beans
The essential characteristics of an enterprise bean are:
-
An enterprise bean typically contains business logic that operates on the enterprise’s data.
-
An enterprise bean’s instances are managed at runtime by a container.
-
An enterprise bean can be customized at deployment time by editing its environment entries.
-
Various service information, such as transaction and security attributes, may be specified together with the business logic of the enterprise bean class in the form of metadata annotations, or separately, in an XML deployment descriptor. This service information may be extracted and managed by tools during application assembly and deployment.
-
Client access is mediated by the container in which the enterprise bean is deployed.
-
If an enterprise bean uses only the services defined by the Enterprise Beans specification, the enterprise bean can be deployed in any compliant Enterprise Beans container. Specialized containers can provide additional services beyond those defined by the Enterprise Beans specification. An enterprise bean that depends on such a service can be deployed only in a container that supports that service.
-
An enterprise bean can be included in an assembled application without requiring source code changes or recompilation of the enterprise bean.
-
The Bean Provider defines a client view of an enterprise bean. The Bean Provider can manually define the client view or it can be generated automatically by application development tools. The client view is unaffected by the container and server in which the bean is deployed. This ensures that both the beans and their clients can be deployed in multiple execution environments without changes or recompilation.
2.3.2. Flexible Model
The enterprise bean architecture is flexible enough to implement the following:
-
An object that represents a stateless service.
-
An object that represents a stateless service and that implements a web service endpoint.
-
An object that represents a stateless service and whose invocation is asynchronous, driven by the arrival of messages.
-
An object that represents a conversational session with a particular client. Such session objects automatically maintain their conversational state across multiple client-invoked methods.
Enterprise beans that are remotely accessible components are intended to be relatively coarse-grained business objects or services (e.g. shopping cart, stock quote service). In general, fine-grained objects should not be modeled as remotely accessible components.
Although the state management protocol defined by the Enterprise Beans architecture is simple, it provides an enterprise bean developer great flexibility in managing a bean’s state.
2.4. Enterprise Bean Object Types
The Enterprise Beans architecture defines the following types of enterprise bean objects:
-
Session objects.
-
Message-driven objects.
-
Entity objects (optional).
Support for session objects and message-driven objects is required by this specification.
Earlier versions of the Enterprise Beans specification required support for entity bean components (not to be confused with the light-weight persistent entities defined by the Jakarta Persistence). Support for entity bean components has been made optional for an implementation as of the 3.2 version of the Enterprise Beans specification and is described in the Enterprise Beans Optional Features document [2].
2.4.1. Session Objects
A typical session object has the following characteristics:
-
Executes on behalf of a single client.
-
Can be transaction-aware.
-
Updates shared data in an underlying database.
-
Does not represent directly shared data in the database, although it may access and update such data.
-
May be relatively short-lived, or may have the same lifetime as that of the application.
-
Is removed when the Enterprise Beans container crashes. The client has to re-establish a new session object to continue computation.
A typical Enterprise Beans container provides a scalable runtime environment to execute a large number of session objects concurrently.
The Enterprise Beans specification defines stateful, stateless, and singleton session beans. There are differences in the API between stateful session beans, stateless session beans, and singleton session beans.
2.4.2. Message-Driven Objects
A typical message-driven object has the following characteristics:
-
Executes upon receipt of a single client message.
-
Is asynchronously invoked.
-
Can be transaction-aware.
-
May update shared data in an underlying database.
-
Does not represent directly shared data in the database, although it may access and update such data.
-
Is relatively short-lived.
-
Is stateless.
-
Is removed when the Enterprise Beans container crashes. The container has to re-establish a new message-driven object to continue computation.
A typical Enterprise Beans container provides a scalable runtime environment to execute a large number of message-driven objects concurrently.
2.4.3. Entity Objects (Optional)
A typical entity object has the following characteristics:
-
Is part of a domain model, providing an object view of data in the database.
-
Can be long-lived (lives as long as the data in the database).
-
The entity and its primary key survive the crash of the Enterprise Beans container. If the state of an entity was being updated by a transaction at the time the container crashed, the entity’s state is restored to the state of the last committed transaction when the entity is next retrieved.
See the Enterprise Beans Optional Features [2] document for details.
2.5. Mapping to Web Service Protocols
To support web service interoperability, the Enterprise Beans specification requires compliant implementations to support XML-based web service invocations using WSDL and SOAP or plain XML over HTTP in conformance with the requirements of the Jakarta® XML Web Services [4], Jakarta® Enterprise Web Services [5], and Jakarta® Web Services Metadata [6] specifications.
2.6. Pruning the Enterprise Beans API
The Jakarta® EE Platform adopted the process defined by the Java SE group for "pruning" technologies from the platform in a careful and orderly way that minimizes the impact to developers using these technologies while allowing the platform to grow even stronger.
The result of pruning a feature is not the actual deletion of the feature but rather the conversion of the feature from a required part of the Enterprise Beans API into an optional part of the Enterprise Beans API. No actual removal from the specification occurs, although the feature may be removed from products at the choice of the product vendor.
Support for the following features has been made optional in the Enterprise Beans specification as of the 3.2 release and the content of the related chapters had been moved to the separate Enterprise Beans Optional Features document [2]. An implementation of this specification is therefore not required to support any of these features. However, if an implementation chooses to implement an optional feature, it must do so in accordance with the requirements of this specification.
-
Enterprise Beans 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence
-
Enterprise Beans 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence
-
Client View of an Enterprise Beans 2.1 and earlier Entity Bean
-
Enterprise Beans QL: Enterprise Beans Query Language for Container-Managed Persistence Query Methods
2.7. Relationship to Jakarta Managed Beans
The Jakarta® Managed Beans [7] defines the minimal requirements for container-managed objects, otherwise known under the acronym "POJOs" (Plain Old Java Objects), within the Jakarta EE Platform. Managed Beans support a small set of basic services, such as resource injection, lifecycle callbacks and interceptors.
A session bean component is a Managed Bean. The Enterprise Beans component model extends the basic Managed Bean model in many areas (component definition, naming, lifecycle, threading, etc.)
2.8. Relationship to Jakarta Contexts and Dependency Injection
The Jakarta® Contexts and Dependency Injection [8] provides a uniform framework for the dependency injection and lifecycle management of "managed beans" and adds contextual lifecycle management to the Enterprise Beans component model.
An Enterprise Beans packaged into a CDI bean archive and
not annotated with jakarta.enterprise.inject.Vetoed
annotation, is
considered a CDI-enabled bean. The CDI container performs dependency
injection on all instances of CDI-enabled session and message-driven
beans, even those which are not contextual instances:
-
A session bean instance obtained via dependency injection is a contextual instance, i.e. it is bound to a lifecycle context and is available to other objects that execute in the same context
-
A message-driven bean instance is always non-contextual, i.e. it may not be injected into other objects.
2.9. Relationship to Jakarta RESTful Web Services
The Jakarta® RESTful Web Services [9] defines a set of Java APIs for the development of Web services built according to the Representational State Transfer (REST) architectural style.
The RESTful Web Services API provides a set of annotations and associated classes and interfaces that may be used to expose beans as Web resources.
In a product that supports the RESTful Web Services specification,
stateless and singleton session beans must be supported
as root resource classes, providers, and jakarta.ws.rs.core.Application
subclasses. RESTful Web Services annotations may be applied to a
session bean class, methods of a session bean’s no-interface view, or
a session bean’s local business interface.
3. Client View of a Session Bean
This chapter describes the client view of a session bean. The session bean itself implements the business logic. The bean’s container provides functionality for remote access, security, concurrency, transactions, and so forth.
While classes implemented by the container provide the client view of the session bean, the container itself is transparent to the client.
3.1. Overview
For a client, a session object is a non-persistent object that implements some business logic running on the server. One way to think of a session object is as a logical extension of the client program that runs on the server. A stateless or stateful session bean object is not shared among multiple clients.
A client can invoke a session bean
synchronously or asynchronously. An asynchronous method can return a
Future<V>
object that allows the client to retrieve a result value,
check for exceptions, or attempt to cancel an in-progress invocation.
From its creation until destruction, a session object lives in a container. The container provides security, concurrency, transactions, swapping to secondary storage, and other services for the session object transparently to the client.
Each session object has an identity which, in general, does not survive a crash and restart of the container, although a high-end container implementation can mask container and server crashes to a remote or web service client.
A client never directly accesses instances of the session bean’s class. A client accesses a session object through the session bean’s client view.
The client view of a session object is independent of the implementation of the session bean and the container.
The client of a session bean may be a local client, a remote client, or a web service client, depending on the view(s) provided by the bean and used by the client.
Multiple enterprise beans can be installed in a container. The container allows the clients of session beans that provide local or remote client views to obtain the business interfaces and/or home interfaces of the installed enterprise beans through dependency injection or to look them up via JNDI.
While it is possible to provide more than one client view for a session bean, typically only one will be provided.
A remote client of an session bean can be another enterprise bean deployed in the same or different container; or it can be an arbitrary Java program, such as an application, applet, or servlet. The client view of a session bean can also be mapped to non-Java client environments, such as CORBA clients that are not written in the Java programming language.
The interface used by a remote client of a session bean is implemented by the container as a remote business interface (or a remote EJBObject interface), and the remote client view of a session bean is location-independent. A client running in the same JVM as the session object uses the same API as a client running in a different JVM on the same or different machine.
Use of a session bean’s local client view entails the collocation of the local client and the session. The local client of an enterprise bean must be collocated in the same container as the bean. The local client view is not location-independent.
The client of a stateless session bean or singleton session bean may be a web service client. Only a stateless session bean or singleton session bean may provide a web service client view. A web service client makes use of the enterprise bean’s web service client view, as described by a WSDL document. The bean’s client view web service endpoint is in terms of a Jakarta XML Web Services endpoint [4]. Web service clients are discussed in Web Service Clients and The Web Service Client View of a Stateless or Singleton Session Bean.
The considerations that should be taken into account in determining the client view to be used for a session bean are further described in Local, Remote, and Web Service Client Views.
3.2. Local, Remote, and Web Service Client Views
This section describes some of the considerations the Bean Provider should take into account in determining the client view to provide for an enterprise bean.
Terminology note:
Enterprise Beans 3.0 significantly simplified the client view of a session bean. This specification distinguishes among the client view interfaces that were defined by the Enterprise Beans 3.0 and later API and the Enterprise Beans 2.1 and earlier API as follows:
-
The term remote business interface is used to refer to the business interface of an Enterprise Beans 3.x session bean that supports remote access.
-
The term remote component interface is used to refer to the remote component interface of the Enterprise Beans 2.1 client view. This interface is an EJBObject interface.
-
The term local business interface refers to the local business interface of an Enterprise Beans 3.x session bean that supports local access.
-
The term local component interface is used to refer to the local component interface of the Enterprise Beans 2.1 client view. This interface is an EJBLocalObject interface.
-
The term business interface is used to refer to a local or remote business interface.
-
The term component interface is used to refer to a local or remote component interface (EJBLocalObject or EJBObject interface).
-
The term business method is used to refer to a method of an enterprise bean that is available for client execution. It may be a method exposed by the local or remote business interface, by the no-interface view, by the local component interface, by the remote component interface, or by the web service client view.
3.2.1. Remote Clients
The remote client view of an enterprise bean is location independent. A client running in the same JVM as a bean instance uses the same API to access the bean as a client running in a different JVM on the same or different machine.
The arguments and results of the methods of the remote interfaces are passed by value.
For a session bean client and component written to the Enterprise Beans 3.x API, a remote client accesses a session bean through the bean’s remote business interface. For a session bean client and component written to the Enterprise Beans 2.1 and earlier APIs, the remote client accesses the session bean through the session bean’s remote home and remote component interfaces.
Compatibility Note: The Enterprise Beans 2.1 and earlier API required that a remote client access the stateful or stateless session bean by means of the session bean’s remote home and remote component interfaces. These interfaces remain available for use with Enterprise Beans 3.x beans, and are described in Remote and Local Client View of Session Beans Written to the Enterprise Beans 2.1 Client View API.
3.2.2. Local Clients
Session beans may have local clients. A local client is a client that is collocated in the same JVM with the session bean that provides the local client view and which may be tightly coupled to the bean. A local client of a session bean may be another enterprise bean or a web component.
Access to an enterprise bean through the local client view requires the collocation in the same JVM of both the local client and the enterprise bean that provides the local client view. The local client view therefore does not provide the location transparency provided by the remote client view.
Access to an enterprise bean through the local client view is only required to be supported for local clients packaged within the same application as the enterprise bean that provides the local client view. Compliant implementations of this specification may optionally support access to the local client view of an enterprise bean from a local client packaged in a different application. The configuration requirements for inter-application access to the local client view are vendor-specific and are outside the scope of this specification. Applications relying on inter-application access to the local client view are non-portable.
The arguments and results of the methods of the local client view are passed "by reference".[2] Enterprise beans that provide a local client view should therefore be coded to assume that the state of any Java object that is passed as an argument or result is potentially shared by caller and callee.
For a session bean client and component
written to the Enterprise Beans 3.x API, a local client accesses a session bean
through the bean’s local business interface or through a no-interface
client view representing all non-static public
methods of the bean class. For a session bean client and component
written to the Enterprise Beans 2.1 and earlier APIs, the local client accesses the
enterprise bean through the bean’s local home and local component
interfaces. The container object that implements a local interface or
the no-interface local view is a local Java object.
Compatibility Note: The Enterprise Beans 2.1 and earlier API required that a local client access a stateful or stateless session bean by means of the session bean’s local home and local component interfaces. These interfaces remain available for use with Enterprise Beans 3.x beans, and are described in Remote and Local Client View of Session Beans Written to the Enterprise Beans 2.1 Client View API.
3.2.3. Choosing Between a Local or Remote Client View
The following considerations should be taken into account in determining whether a local or remote access should be used for an enterprise bean.
-
The remote programming model provides location independence and flexibility with regard to the distribution of components in the deployment environment. It provides a loose coupling between the client and the bean.
-
Remote calls involve pass-by-value. This copy semantics provides a layer of isolation between caller and callee, and protects against the inadvertant modification of data. The client and the bean may be programmed to assume this parameter copying.
-
Remote calls are potentially expensive. They involve network latency, overhead of the client and server software stacks, argument copying, etc. Remote calls are typically programmed in a coarse-grained manner with few interactions between the client and bean.
-
The objects that are passed as parameters on remote calls must be serializable.
-
When the Enterprise Beans 2.1 and earlier remote home and remote component interfaces are used, the narrowing of remote types requires the use of
javax.rmi.PortableRemoteObject.narrow
rather than Java language casts. -
Remote calls may involve error cases due to communication, resource usage on other servers, etc., which are not expected in local calls. When the Enterprise Beans 2.1 and earlier remote home and remote component interfaces are used, the client has to explicitly program handlers for handling the
java.rmi.RemoteException
. -
Because of the overhead of the remote programming model, it is typically used for relatively coarse-grained component access.
-
Local calls involve pass-by-reference. The client and the bean may be programmed to rely on pass-by-reference semantics. For example, a client may have a large document which it wants to pass on to the bean to modify, and the bean further passes on. In the local programming model the sharing of state is possible. On the other hand, when the bean wants to return a data structure to the client but the bean does not want the client to modify it, the bean explicitly copies the data structure before returning it, while in the remote programming model the bean does not copy the data structure because it assumes that the system will do the copy.
-
Because local calls involve pass-by-reference, the local client and the enterprise bean providing the local client view are collocated.
-
The collocation entailed by the local programming model means that the enterprise bean cannot be deployed on a node different from that of its client—thus restricting the distribution of components.
-
Because the local programming model provides more lightweight access to a component, it better supports more fine-grained component access.
The choice between the local and the remote programming model is a design decision that the Bean Provider makes when developing the enterprise bean.
While it is possible to provide both a remote client view and a local client view for an enterprise bean, more typically only one or the other will be provided.
3.2.4. Web Service Clients
Stateless session beans and singleton session beans may have web service clients.
A web service client accesses a session bean through the web service client view. The web service client view is described by the WSDL document for the web service that the bean implements. WSDL is an XML format for describing a web service as a set of endpoints operating on messages. The abstract description of the service is bound to an XML based protocol (SOAP [11]) and underlying transport (HTTP or HTTPS) by means of which the messages are conveyed between client and server. (See references [12], [6], [5], [4]).
The web service methods of a session bean provide the basis of the web service client view of the bean that is exported through WSDL. See reference [6] for a description of how Java language metadata annotations may be used to specify a session bean’s web services client view.
A bean’s web service client view may be initially defined by a WSDL document and then mapped to a web service endpoint that conforms to this, or an existing bean may be adapted to provide a web service client view. Reference [5] describes various design-time scenarios that may be used for Enterprise Beans web service endpoints.
Compatibility Note: Enterprise Beans 2.1 required the Bean Provider to define a web service endpoint interface for a stateless session bean when he or she wished to expose the functionality of the bean as a web service endpoint through WSDL. This requirement to define the web service endpoint interface is removed in Enterprise Beans 3.0 and later. See [6].
The web service client view of an enterprise bean is location independent and remotable.
Web service clients may be Java clients and/or clients not written in the Java programming language. A web service client that is a Java client accesses the web service by means of the Jakarta XML Web Services client APIs. Access through web service clients occurs through SOAP 1.1, SOAP 1.2 or plain XML over HTTP(S).
While it is possible to provide a web service client view in addition to other client views for an enterprise bean, more typically only one will be provided. There is no prohibition against using the same interface as both a remote business interface and a web service endpoint interface. In that case it is the Bean Provider’s responsibility to ensure that the interface conforms to the type requirements of each client view through which it is exposed.
3.3. Enterprise Beans Container
An Enterprise Beans container (container for short) is a system that functions as the "container" for enterprise beans. Multiple enterprise beans can be deployed in the same container. The container is responsible for making the business interfaces and/or home interfaces of its deployed enterprise beans available to the client through dependency injection and/or through lookup in the JNDI namespace.
3.4. Client View of Session Beans Written to the Enterprise Beans 3.x Simplified API
The Enterprise Beans 3.x local or remote client of a
session bean written to the Enterprise Beans 3.x API accesses a session bean through
its business interface. The business interface of an Enterprise Beans 3.x session
bean is an ordinary Java interface, regardless of whether local or
remote access is provided for the bean. In particular, the Enterprise Beans 3.x
session bean business interface is not one of the interface types
required by earlier versions of the Enterprise Beans specification (i.e., EJBObject
or EJBLocalObject interface). A local client may also access a session
bean through a no-interface view that exposes all non-static public
methods of the bean class.
3.4.1. Obtaining a Session Bean’s Business Interface
A client can obtain a session bean’s business interface through dependency injection or lookup in the JNDI namespace.
For example, the business interface Cart
for the CartBean
session bean may be obtained using dependency
injection as follows:
@EJB
Cart cart;
The Cart
business interface could also be
looked up using JNDI as shown in the following code segment using the
lookup
method provided by the EJBContext
interface. In this example,
a reference to the client bean’s SessionContext
object is obtained
through dependency injection:
@Resource
SessionContext ctx;
...
Cart cart = (Cart)ctx.lookup("cart");
In both cases, the syntax used in obtaining
the reference to the Cart
business interface is independent of whether
the business interface is local or remote. In the case of remote access,
the actual location of a referenced enterprise bean and Enterprise Beans container
are, in general, transparent to the client using the remote business
interface of the bean.
3.4.2. Obtaining a Reference to the No-interface View
A client can obtain a reference to a session bean’s no-interface view through dependency injection or lookup in the JNDI namespace.
For example, the no-interface view of the
CartBean
session bean with bean class com.acme.CartBean
may be
obtained using dependency injection as follows:
@EJB
CartBean cart;
The CartBean
no-interface view could also
be looked up via JNDI as shown in the following code segment using the
lookup
method provided by the EJBContext
interface. In this example, a
reference to the client bean’s SessionContext
object is obtained through
dependency injection:
@Resource
SessionContext ctx;
...
CartBean cart = (CartBean)ctx.lookup("cart");
Despite the fact that the client reference
for the no-interface view has the type of the bean class, the client
never directly uses the new
operator to acquire the reference.
3.4.3. Session Bean’s Business Interface
The session bean’s business interface is an ordinary Java interface. It contains the business methods of the session bean.
A reference to a session bean’s business interface may be passed as a parameter or return value of a business interface method. If the reference is to a session bean’s local business interface, the reference may only be passed as a parameter or return value of a local business interface method or a no-interface view method.
The business interface of a stateful session bean typically contains a method to initialize the state of the session object and a method to indicate that the client has finished using the session object and that it can be removed. See Session Bean Component Contract.
It is invalid to reference a session object
that does not exist. If a stateful session bean has been removed,
attempted invocations on the stateful session bean business interface
result in the
jakarta.ejb.NoSuchEJBException
.[3]
If a singleton session bean did not successfully initialize, attempted
invocations on the singleton session bean business interface result in
the jakarta.ejb.NoSuchEJBException
.
The container provides an implementation of a session bean’s business interface such that when the client invokes a method on the instance of the business interface, the business method on the session bean instance and any interceptor methods are invoked as needed.
The container makes the session bean’s business interface available to the Enterprise Beans 3.x client through dependency injection and through lookup in the JNDI namespace. Enterprise Bean References describes in further detail how clients can obtain references to Enterprise Beans business interfaces.
3.4.4. Session Bean’s No-Interface View
A session bean’s no-interface view is a
variation of the local view that exposes the non-static public
methods
of the bean class without the use of a separate business interface.
A reference to the no-interface view may be passed as a parameter or return value of any local business interface or no-interface view method.
The container provides an implementation of a
reference to a no-interface view such that when the client invokes a
method on the reference, the business method on the session bean
instance and any interceptor methods are invoked as needed. As with the
session bean remote and local views, a client acquires a no-interface
view reference via lookup or injection only. A client does not directly
instantiate (use the new
operator on) the bean class to acquire a
reference to the no-interface view.
Only public
methods of the bean class and of
any superclasses except java.lang.Object
may be invoked through the
no-interface view. Attempted invocations of methods with any other
access modifiers via the no-interface view reference must result in the
jakarta.ejb.EJBException
.
When interacting with a reference to the no-interface view, the client must not make any assumptions regarding the internal implementation of the reference, such as any instance-specific state that may be present in the reference. Although the reference object is type-compatible with the corresponding bean class type, there is no prescribed relationship between the internal implementation of the reference and the implementation of the bean instance.
The developer of an enterprise bean that
exposes a no-interface view must not make any assumptions about the
number of times the bean class no-arg constructor will be called. For
example, it is possible that the acquisition of a client reference to
the no-interface view will result in the invocation of the bean class
constructor. It is recommended that the Bean Provider place component
initialization logic in a PostConstruct
method instead of the bean class
no-arg constructor.
It is invalid to reference a session object
that does not exist. If a stateful session bean has been removed,
attempted invocations on the no-interface view reference must result in
the jakarta.ejb.NoSuchEJBException
. If a singleton session bean did not
successfully initialize, attempted invocations on the singleton session
bean’s no-interface view reference result in the
jakarta.ejb.NoSuchEJBException
.
3.4.5. Client View of Session Object’s Life Cycle
From the point of view of the client, a session object exists once the client has obtained a reference to its business interface—whether through dependency injection or from lookup of the business interface in JNDI.
A client that has a reference to a session object’s business interface can then invoke business methods on the interface and/or pass the reference as a parameter or return value of a business interface method.[4]
A client may remove a stateful session bean
by invoking a method of its business interface designated as a Remove
method.
The lifecycle of a stateless session bean does not require that it be removed by the client. Removal of a stateless session bean instance is performed by the container, transparently to the client.
The lifecycle of a singleton session bean does not require that it be removed by the client. Removal of a singleton session bean instance is performed by the container, transparently to the client.
The contracts for session bean lifecycle are described in Session Bean Component Contract.
3.4.6. Example of Obtaining and Using a Session Object
An example of the session bean runtime objects is illustrated by the following diagram:
A client obtains a reference to a Cart
session object, which provides a shopping service, by means of
dependency injection or using JNDI lookup. The client then uses this
session object to fill the cart with items and to purchase its contents.
Cart
is a stateful session.
In this example, the client obtains a
reference to the Cart
’s business interface through dependency
injection. The client then uses the business interface to initialize the
session object and add a few items to it. The startShopping
method is
a business method that is provided for the initialization of the session
object.
@EJB
Cart cart;
...
cart.startShopping();
cart.addItem(66);
cart.addItem(22);
Finally the client purchases the contents of the shopping cart, and finishes the shopping activity.[5]
cart.purchase();
cart.finishShopping();
3.4.7. Session Object Identity
A client can test two Enterprise Beans 3.x remote or local
view references for identity by means of the Object.equals
and
Object.hashCode
methods.
3.4.7.1. Stateful Session Beans
A stateful session object has a unique
identity that is assigned by the container at the time the object is
created. A client of the stateful session bean business interface can
determine if two business interface or no-interface view references
refer to the same session object by use of the equals
method.
For example,
@EJB
Cart cart1;
@EJB
Cart cart2;
...
if (cart1.equals(cart1)) { // this test must return true
...
}
...
if (cart1.equals(cart2)) { // this test must return false
...
}
All stateful session bean references to the same business interface for the same stateful session bean instance will be equal. All references to the no-interface view of the same stateful session bean instance will be equal. Stateful session bean references to different interface types or between an interface type and a no-interface view or to different stateful session bean instances will not have the same identity.
3.4.7.2. Stateless Session Beans
All business object references of the same interface type for the same stateless session bean have the same object identity, which is assigned by the container. All references to the no-interface view of the same stateless session bean have the same object identity.
For example,
@EJB
Cart cart1;
@EJB
Cart cart2;
...
if (cart1.equals(cart1)) { // this test must return true
...
}
...
if (cart1.equals(cart2)) { // this test must also return true
...
}
The equals
method always returns true
when
used to compare references to the same business interface type of the
same stateless session bean. The equals
method always returns true
when
used to compare references to the no-interface view of the same
stateless session bean. Stateless session bean references to either
different business interface types or between an interface type and a
no-interface view or to different session beans will not be equal.
3.4.7.3. Singleton Session Beans
All business object references of the same interface type for the same singleton session bean have the same object identity, which is assigned by the container. All references to the no-interface view of the same singleton session bean have the same object identity.
For example,
@EJB
Shared shared1;
@EJB
Shared shared2;
...
if (shared1.equals(shared1)) { // this test must return true
...
}
...
if (shared1.equals(shared2)) { // this test must also return true
...
}
The equals
method always returns true
when
used to compare references to the same business interface type of the
same singleton session bean. The equals
method always returns true
when
used to compare references to the no-interface view of the same
singleton session bean. Session bean references to either different
business interface types or between an interface type and a no-interface
view or to different session beans will not be equal.
3.4.8. Asynchronous Invocations
By default, session bean invocations through the remote, local, and no-interface views are synchronous. The client blocks for the duration of the invocation and is returned control only after all invocation processing has completed. Clients can achieve asynchronous invocation behavior by invoking session bean methods that have been designed to support asynchrony.
When a client invokes an asynchronous method, the container returns control to the client immediately and continues processing the invocation on a separate thread of execution.
The client should expect to receive a system
exception (in the form of the jakarta.ejb.EJBException
) on the client
thread if the container has problems allocating the internal resources
required to support the asynchronous method.[6]
If a
system exception is received on the client thread, the client can expect
that the container will not be able to dispatch the asynchronous method.
The client may wish to retry the asynchronous method at a later time.
If no system exception is received, the
client can expect that the container will make an attempt to dispatch
the asynchronous method. An exception resulting from the asynchronous
method execution (e.g. an authorization failure, transaction commit
failure, application exception, etc.) will be available via the
Future<V>
object.
3.4.8.1. Return Values
Asynchronous methods have a return type of
void
or Future<V>
, where V
represents the result value of the
asynchronous invocation.
For Future<V>
, the object returned from the
client invocation is a container provided object. This object allows the
client to retrieve the invocation result value, discover any invocation
exception, or attempt to cancel the asynchronous invocation.
All methods of the java.util.concurrent.Future
interface are supported.
Unless otherwise noted, the behavior matches that described in its
javadoc entry [13].
Future.cancel(boolean mayInterruptIfRunning)
If a client calls cancel
on its Future
object, the container will attempt to cancel the associated asynchronous
invocation only if that invocation has not already been dispatched.
There is no guarantee that an asynchronous invocation can be cancelled,
regardless of how quickly cancel
is called after the client receives its
Future object. If the asynchronous invocation cannot be cancelled, the
method must return false
. If the asynchronous invocation is successfully
cancelled, the method must return true
.
The mayInterruptIfRunning
flag controls
whether, in the case that the asynchronous invocation can not be
cancelled, the target enterprise bean should have visibility to the
client’s cancel attempt. If the mayInterruptIfRunning
flag is set to
true
, then subsequent calls to the SessionContext.wasCancelCalled
method
from within the associated dispatched asynchronous invocation must
return true
. If the mayInterruptIfRunning
flag is set to false
, then
subsequent calls to the SessionContext.wasCancelCalled
method from
within the associated dispatched asynchronous invocation must return
false
.
Note that all the client Future
cancel
semantics (isCancelled
, CancellationException
, etc.) depend only on the
result of Future.cancel
. If the dispatched asynchronous method does
decide to short circuit its processing as a result of checking
SessionContext
, it is the responsibility of the Bean Provider to decide
how to convey that information to the client. Typically, that is done
through a special return value or exception delivered via Future.get()
.
Future.get
The client calls one of the two Future.get
methods in order to retrieve the result value or resulting exception
from the associated asynchronous invocation. This specification
recommends that unless the client successfully cancels the asynchronous
invocation it should call get
on every Future
object it receives. If a
call to get successfully returns a result value or throws an
ExecutionException
, all subsequent calls to get on the same Future
object must result in that same behavior.
The Enterprise Beans Container Provider is permitted to define a timeout value that governs the maximum amount of time the container maintains result values for completed asynchronous invocations. The configuration of such a timeout is beyond the scope of this specification.
3.4.9. Concurrent Access to Session Bean References
It is permissible to acquire a session bean reference and attempt to invoke the same reference object concurrently from multiple threads. However, the resulting client behavior on each thread depends on the concurrency semantics of the target bean. See Serializing Session Bean Methods and Singleton Session Bean Concurrency for details of the concurrency behavior for session beans.
3.5. The Web Service Client View of a Stateless or Singleton Session Bean
From the perspective of the client, the existence of the stateless session bean or singleton session bean is completely hidden behind the web service endpoint that the bean implements.
The web service client’s access to the web service functionality provided by a session bean occurs through a web service endpoint. In the case of Java clients, this endpoint is accessed as a Jakarta XML Web Services service endpoint using the client view APIs, as described in [4].
The following diagram illustrates the view that is provided to Jakarta XML Web Services clients of a stateless session bean through the client view APIs.
3.5.1. Jakarta XML Web Services Clients
The Jakarta XML Web Services client obtains a
reference to the service instance of the jakarta.xml.ws.Service
class
through dependency injection or using JNDI. The service class can be a
generic jakarta.xml.ws.Service
class or a generated service class which
extends the jakarta.xml.ws.Service
class. The service instance is then
used to obtain a port object for the web service endpoint. The
mechanisms and APIs for client web service access are described in the
Jakarta XML Web Services [4] specification and in the
Jakarta Enterprise Web Services [5] specification.
The following example illustrates how a Jakarta XML Web Services client obtains a reference to a web service endpoint, obtains a port object for the web service endpoint, and invokes a method on that endpoint.
@WebServiceRef
public StockQuoteService stockQuoteService;
...
StockQuoteProvider sqp = stockQuoteService.getStockQuoteProviderPort();
float quotePrice = sqp.getLastTradePrice("ACME");
...
The use of service references and the
WebServiceRef
annotation are described in further detail in [4].
3.6. Remote and Local Client View of Session Beans Written to the Enterprise Beans 2.1 Client View API
The remainder of this chapter describes the session bean client view defined by the Enterprise Beans 2.1 and earlier specifications. Support for the definition and use of these earlier client interfaces is required to be provided by implementations of this specification. The Enterprise Beans 2.1 remote and local client views are not supported for singleton session beans.
3.6.1. Locating a Session Bean’s Home Interface
The Enterprise Beans 2.1 and earlier specifications
required that the client first obtain a reference to a session bean’s
home interface, and then use the home interface to obtain a reference to
the bean’s component interface. This earlier programming model continues
to be supported by this specification. Both dependency injection and use
of the EJBContext lookup
method may be used as an alternative to the
JNDI APIs to obtain a reference to the home interface.
For example, an Enterprise Beans 3.x client,
com.acme.example.MySessionBean
, might obtain a reference to a bean’s
home interface as follows:
@EJB
CartHome cartHome;
This home interface could be looked up in
JNDI using the EJBContext lookup
method as shown in the following code
segment:
@Resource
SessionContext ctx;
...
CartHome cartHome =
(CartHome)ctx.lookup("com.acme.example.MySessionBean/cartHome");
When the EJBContext lookup
method is used
to look up a home interface, the use of
javax.rmi.PortableRemoteObject.narrow
is not required.
The following code segments illustrate how
the home interface is obtained when the JNDI APIs are used directly, as
was required in the Enterprise Beans 2.1 programming model. For example, the remote
home interface for the Cart
session bean can be located using the
following code segment:
Context initialContext = new InitialContext();
CartHome cartHome = (CartHome)javax.rmi.PortableRemoteObject.narrow(
initialContext.lookup("java:comp/env/ejb/cart"), CartHome.class);
If the Cart
session bean provides a local
client view instead of a remote client view and CartHome
is a local
home interface, this lookup might be as follows:
Context initialContext = new InitialContext();
CartHome cartHome =
(CartHome)initialContext.lookup("java:comp/env/ejb/cart");
3.6.2. Session Bean’s Remote Home Interface
This section is specific to session beans that provide a remote client view using the remote component interface and remote home interface.
The container provides the implementation of the remote home interface for each session bean that defines a remote home interface that is deployed in the container. The object that implements a session bean’s remote home interface is called a session EJBHome object. The container makes the session bean’s remote home interface available to the client through dependency injection or through lookup in the JNDI namespace.
The remote home interface allows a client to do the following:
-
Create a new session object.
-
Remove a session object.
-
Get the
jakarta.ejb.EJBMetaData
interface for the session bean. Thejakarta.ejb.EJBMetaData
interface is intended to allow application assembly tools to discover information about the session bean, and to allow loose client/server binding and client-side scripting. -
Obtain a handle for the remote home interface. The home handle can be serialized and written to stable storage. Later, possibly in a different JVM, the handle can be deserialized from stable storage and used to obtain back a reference of the remote home interface.
The life cycle of the distributed object implementing the remote home interface (the EJBHome object) or the local Java object implementing the local home interface (the EJBLocalHome object) is container-specific. A client application should be able to obtain a home interface, and then use it multiple times, during the client application’s lifetime.
A client can pass a remote home object reference to another application. The receiving application can use the home interface in the same way that it would use a remote home object reference obtained via JNDI.
3.6.2.1. Creating a Session Object
A home interface
defines one or more create<METHOD>
methods, one for each way to create a
session object. The arguments of the create
methods are typically used
to initialize the state of the created session object.
The return type of a create<METHOD>
method on
the remote home interface is the session bean’s remote component
interface.
The following example illustrates a remote
home interface that defines two create<METHOD>
methods:
public interface CartHome extends jakarta.ejb.EJBHome {
Cart create(String customerName, String account)
throws RemoteException, BadAccountException, CreateException;
Cart createLargeCart(String customerName, String account)
throws RemoteException, BadAccountException, CreateException;
}
The following example illustrates how a
client creates a new session object using a create<METHOD>
method of
the CartHome
interface:
cartHome.create("John", "7506");
3.6.2.2. Removing a Session Object
A remote client
may remove a session object using the remove()
method of the
jakarta.ejb.EJBObject
interface, or the remove(Handle handle)
method of
the jakarta.ejb.EJBHome
interface.
Because session objects do not have primary
keys that are accessible to clients, invoking the
jakarta.ejb.EJBHome.remove(Object primaryKey)
method on a session results
in a jakarta.ejb.RemoveException
.
3.6.3. Session Bean’s Local Home Interface
This section is specific to session beans that provide a local client view using the local component interface and local home interface.
The container provides the implementation of the local home interface for each session bean that defines a local home interface that is deployed in the container. The object that implements a session bean’s local home interface is called a session EJBLocalHome object. The container makes the session bean’s local home interface available to the client through JNDI.
The local home interface allows a local client to do the following:
-
Create a new session object.
-
Remove a session object.
A client can pass a local home object reference to another application through its local component interface. A local home object reference cannot be passed as an argument or result of a method on an enterprise bean’s remote home or remote component interface.
3.6.3.1. Creating a Session Object
A local home
interface defines one or more create<METHOD>
methods, one for each way
to create a session object. The arguments of the create
methods are
typically used to initialize the state of the created session object.
The return type of a create<METHOD>
method on
the local home interface is the session bean’s local component
interface.
The following example illustrates a local
home interface that defines two create<METHOD>
methods:
public interface CartHome extends jakarta.ejb.EJBLocalHome {
Cart create(String customerName, String account)
throws BadAccountException, CreateException;
Cart createLargeCart(String customerName, String account)
throws BadAccountException, CreateException;
}
The following example illustrates how a
client creates a new session object using a create<METHOD>
method of
the CartHome
interface:
cartHome.create("John", "7506");
3.6.3.2. Removing a Session Object
A local client
may remove a session object using the remove()
method of the
jakarta.ejb.EJBLocalObject
interface.
Because session objects do not have primary
keys that are accessible to clients, invoking the
jakarta.ejb.EJBLocalHome.remove(Object primaryKey)
method on a session
results in a jakarta.ejb.RemoveException
.
3.6.4. EJBObject and EJBLocalObject
A remote or local client that uses the Enterprise Beans 2.1 client view APIs uses the session bean’s component interface to access a session bean instance. The class that implements the session bean’s component interface is provided by the container. Instances of a session bean’s remote component interface are called session EJBObjects. Instances of a session bean’s local component interface are called session EJBLocalObjects.
A session EJBObject supports:
-
The business logic methods of the object. The session EJBObject delegates invocation of a business method to the session bean instance.
-
The methods of the
jakarta.ejb.EJBObject
interface. These methods allow the client to:-
Get the session object’s remote home interface.
-
Get the session object’s handle.
-
Test if the session object is identical with another session object.
-
Remove the session object.
-
A session EJBLocalObject supports:
-
The business logic methods of the object. The session EJBLocalObject delegates invocation of a business method to the session bean instance.
-
The methods of the
jakarta.ejb.EJBLocalObject
interface. These methods allow the client to:-
Get the session object’s local home interface.
-
Test if the session object is identical with another session object.
-
Remove the session object.
-
The implementation of the methods defined in
the jakarta.ejb.EJBObject
and jakarta.ejb.EJBLocalObject
interfaces is
provided by the container. They are not delegated to the instances of
the session bean class.
3.6.5. Client view of Session Object’s Life Cycle
From the point of view of a local or remote client using the Enterprise Beans 2.1 and earlier client view API, the life cycle of a session object is illustrated below.
A session object does not exist until it is created. When a client creates a session object, the client has a reference to the newly created session object’s component interface.
3.6.5.1. References to Session Object Remote Component Interfaces
A client that has a reference to a session object’s remote component interface can then do any of the following:
-
Invoke business methods defined in the session object’s remote component interface.
-
Get a reference to the session object’s remote home interface.
-
Get a handle for the session object.
-
Pass the reference as a parameter or return value within the scope of the client.
-
Remove the session object. A container may also remove the session object automatically when the session object’s lifetime expires.
It is invalid to reference a session
object that does not exist. Attempted remote invocations on a stateful
session object that does not exist result in a
java.rmi.NoSuchObjectException
.[7]
3.6.5.2. References to Session Object Local Component Interfaces
A client that has a reference to a session object’s local component interface can then do any of the following:
-
Invoke business methods defined in the session object’s local component interface.
-
Get a reference to the session object’s local home interface.
-
Pass the reference as a parameter or return value of a local component interface method.
-
Remove the session object. A container may also remove the session object automatically when the session object’s lifetime expires.
It is invalid to reference a session
object that does not exist. Attempted invocations on a stateful session
object that does not exist result in
jakarta.ejb.NoSuchObjectLocalException
.[8]
A client can pass a local object reference or local home object reference to another application through its local component interface. A local object reference or local home object reference cannot be passed as an argument or result of a method on an enterprise bean’s remote home or remote component interface.
3.6.6. Creating and Using a Session Object
An example of the session bean runtime objects is illustrated by the following diagram:
A client creates a remote Cart
session
object, which provides a shopping service, using a create<METHOD>
method
of the Cart
’s remote home interface. The client then uses this
session object to fill the cart with items and to purchase its contents.
Suppose that the end-user wishes to start the
shopping session, suspend the shopping session temporarily for a day or
two, and later complete the session. The client might implement this
feature by getting the session object’s handle, saving the serialized
handle in persistent storage, and using it later to reestablish access
to the original Cart
.
For the following example, we start by
looking up the Cart
’s remote home interface in JNDI. We then use the
remote home interface to create a Cart
session object and add a few
items to it:
CartHome cartHome = (CartHome)javax.rmi.PortableRemoteObject.narrow(
initialContext.lookup(...), CartHome.class);
Cart cart = cartHome.createLargeCart(...);
cart.addItem(66);
cart.addItem(22);
Next we decide to complete this shopping session at a later time so we serialize a handle to this cart session object and store it in a file:
Handle cartHandle = cart.getHandle();
//serialize cartHandle, store in a file...
Finally we deserialize the handle at a later time, re-create the reference to the cart session object, and purchase the contents of the shopping cart:
Handle cartHandle = ...; // deserialize from a file...
Cart cart = (Cart)javax.rmi.PortableRemoteObject.narrow(
cartHandle.getEJBObject(), Cart.class);
cart.purchase();
cart.remove();
3.6.7. Object Identity
Session objects
are intended to be private resources used only by the client that
created them. For this reason, session objects, from the client’s
perspective, appear anonymous. Session objects do not expose their
identity as a primary key, on the opposite, they hide their identity. As
a result, the EJBObject.getPrimaryKey()
method results in a java.rmi.RemoteException
and the
EJBLocalObject.getPrimaryKey()
method
results in a jakarta.ejb.EJBException
, and the
EJBHome.remove(Object primaryKey)
and the
EJBLocalHome.remove(Object primaryKey)
methods
result in a jakarta.ejb.RemoveException
if called on a session bean. If
the EJBMetaData.getPrimaryKeyClass()
method is invoked on a
EJBMetaData
object for a session bean, the method throws the
java.lang.RuntimeException
.Since all session objects hide their
identity, there is no need to provide a finder for them. The home
interface of a session bean must not define any finder methods.
A session object handle can be held beyond the life of a client process by serializing the handle to persistent storage. When the handle is later deserialized, the session object it returns will work as long as the session object still exists on the server. (An earlier timeout or server crash may have destroyed the session object.) A handle is not a capability, in the security sense, that would automatically grant its holder the right to invoke methods on the object. When a reference to a session object is obtained from a handle, and then a method on the session object is invoked, the container performs the usual access checks based on the caller’s principal.
3.6.7.1. Stateful Session Beans
A stateful session object has a unique identity that is assigned by the container at create time.
A remote client
can determine if two remote object references refer to the same session
object by invoking the isIdentical(EJBObject otherEJBObject)
method
on one of the references. A local client can determine if two local
object references refer to the same session object by invoking the
isIdentical(EJBLocalObject otherEJBLocalObject)
method.
The following example illustrates the use of
the isIdentical
method for a stateful session object.
FooHome fooHome = ...; // obtain home of a stateful session bean
Foo foo1 = fooHome.create(...);
Foo foo2 = fooHome.create(...);
if (foo1.isIdentical(foo1)) { // this test must return true
...
}
if (foo1.isIdentical(foo2)) { // this test must return false
...
}
3.6.7.2. Stateless Session Beans
All session objects of the same stateless session bean within the same home have the same object identity, which is assigned by the container. If a stateless session bean is deployed multiple times (each deployment results in the creation of a distinct home), session objects from different homes will have a different identity.
The isIdentical(EJBObject otherEJBObject)
and isIdentical(EJBLocalObject otherEJBLocalObject)
methods always
returns true when used to compare object references of two session
objects of the same stateless session bean.
The following example illustrates the use of
the isIdentical
method for a stateless session object.
FooHome fooHome = ...; // obtain home of a stateless session bean
Foo foo1 = fooHome.create();
Foo foo2 = fooHome.create();
if (foo1.isIdentical(foo1)) { // this test returns true
...
}
if (foo1.isIdentical(foo2)) { // this test returns true
...
}
3.6.7.3. getPrimaryKey()
The object
identifier of a session object is, in general, opaque to the client. The
result of getPrimaryKey()
on a session EJBObject reference results in
java.rmi.RemoteException
. The result of getPrimaryKey()
on a
session EJBLocalObject reference results in jakarta.ejb.EJBException
.
3.6.8. Type Narrowing
A client
program that is intended to be interoperable with all compliant Enterprise Beans
container implementations must use the
javax.rmi.PortableRemoteObject.narrow
method to perform type-narrowing
of the client-side representations of the remote home and remote
component interfaces.[9]
Note: Programs using the cast operator for narrowing the remote component interface and remote home interface are likely to fail if the container implementation uses RMI-IIOP as the underlying communication transport.
4. Session Bean Component Contract
This chapter specifies the contract between a session bean and its container. It defines the life cycle of the session bean instances.
This chapter defines the developer’s view of session bean state management and the container’s responsibilities for managing session bean state.
4.1. Overview
A session bean instance is an instance of the session bean class. It holds the session object’s state.
A session bean instance is an extension of the client that creates it:
-
In the case of a stateful session bean, its fields contain conversational state on behalf of the session object’s client. This state describes the conversation represented by a specific client/session object pair.
-
It typically reads and updates data in a database on behalf of the client.
-
In the case of a stateful session bean, its lifetime is controlled by the client.
Typically, a session object’s conversational state is not written to the database. A session Bean Provider simply stores it in the session bean instance’s fields and assumes its value is retained for the lifetime of the instance. A developer may use an extended persistence context to store a stateful session bean’s persistent conversational state. See the document "Jakarta Persistence" specification [3].
A session bean that does not make use of Jakarta Persistence must
explicitly manage cached database data. A session bean
instance must write any cached database updates prior to a transaction
completion, and it must refresh its copy of any potentially stale
database data at the beginning of the next transaction. A session bean
must also refresh any java.sql.Statement
objects before they are used
in a new transaction context. Use of Jakarta Persistence provides a
session bean with automatic management of database data, including the
automatic flushing of cached database updates upon transaction commit.
See [3].
The container manages the life cycle of the session bean instances. It notifies the instances when bean action may be necessary, and it provides a full range of services to ensure that the session bean implementation is scalable and can support a large number of clients.
A session bean may be invoked either synchronously or asynchronously.
A session bean may be either:
-
stateless—the session bean instances contain no conversational state between methods; any instance can be used for any client.
-
stateful—the session bean instances contain conversational state which must be retained across methods and transactions.
-
singleton—a single session bean instance is shared between clients and supports concurrent access.
4.2. Conversational State of a Stateful Session Bean
The conversational state of a stateful session object is defined as the session bean instance’s field values, its associated interceptors and their instance field values, plus the transitive closure of the objects from these instances’ fields reached by following Java object references.
To efficiently manage the size of its working set, a session bean container may need to temporarily transfer the state of an idle stateful session bean instance to some form of secondary storage. The transfer from the working set to secondary storage is called instance passivation. The transfer back is called activation.
In advanced cases, a session object’s
conversational state may contain open resources, such as open sockets
and open database cursors. A container cannot retain such open resources
when a session bean instance is passivated. A developer of a stateful
session bean must close and open the resources in the PrePassivate
and
PostActivate
lifecycle callback interceptor
methods.[10]
A container may only passivate a stateful session bean instance when the instance is not in a transaction.
A container must not passivate a stateful session bean that is designated as not passivation capable. See Disabling Passivation of Stateful Session Beans on how to disable passivation of stateful session beans.
A container must not passivate a stateful session bean with an extended persistence context unless the following conditions are met:[11]
-
All the entities in the persistence context are serializable.
-
The EntityManager is serializable.
A stateless session bean is never passivated.
A singleton session bean is never passivated.
4.2.1. Instance Passivation and Conversational State
The Bean Provider
is required to ensure that the PrePassivate
method leaves the instance
fields and the fields of its associated interceptors ready to be
serialized by the container. The objects that are assigned to the
instance’s non-transient fields and the non-transient fields of
its interceptors after the PrePassivate
method completes must be one
of the following.
-
A serializable object.[12]
-
A
null
. -
A reference to an enterprise bean’s local or remote business interface.
-
A reference to an enterprise bean’s no-interface view.
-
A reference to an enterprise bean’s remote component interface, even if the stub class is not serializable.
-
A reference to an enterprise bean’s remote home interface, even if the stub class is not serializable.
-
A reference to an entity bean’s [12] local component interface, even if it is not serializable.
-
A reference to an entity bean’s [13] local home interface, even if it is not serializable.
-
A reference to the
SessionContext
object, even if it is not serializable. -
A reference to the environment naming context (that is, the
java:comp/env
JNDI context) or any of its subcontexts. -
A reference to the
UserTransaction
interface. -
A reference to a resource manager connection factory.[14]
-
A reference to a container-managed
EntityManager
object, even if it is not serializable. -
A reference to an
EntityManagerFactory
object obtained via injection or JNDI lookup, even if it is not serializable. -
A reference to a
jakarta.ejb.Timer
object. -
An object that is not directly serializable, but becomes serializable by replacing the references to an enterprise bean’s business interface, an enterprise bean’s home and component interfaces, the references to the
SessionContext
object, the references to thejava:comp/env
JNDI context and its subcontexts, the references to theUserTransaction
interface, and the references to theEntityManager
and/orEntityManagerFactory
by serializable objects during the object’s serialization.
This means, for example, that the Bean
Provider must close all JDBC™ connections in the PrePassivate
method
and assign the instance’s fields storing the connections to null
.
The last bulleted item covers cases such as storing Collections of component interfaces in the conversational state.
The Bean Provider must assume that the
content of transient
fields may be lost between the PrePassivate
and
PostActivate
notifications. Therefore, the Bean Provider should not
store in a transient
field a reference to any of the following objects:
SessionContext
object; environment JNDI naming context and any its
subcontexts; business interfaces; home and component interfaces;
EntityManager
interface; EntityManagerFactory
interface;
UserTransaction
interface.
The restrictions on the use of transient fields ensure that containers can use Java Serialization during passivation and activation.
The following are the requirements for the container.
The container performs the Java programming
language Serialization (or its equivalent) of the instance’s state (and
its interceptors’ state) after it invokes the PrePassivate
method on the
instance and its interceptors.
The container must be able to properly save and restore the reference to the business interfaces and home and component interfaces of the enterprise beans stored in the instance’s state even if the classes that implement the object references are not serializable.
The container may use, for example, the
object replacement technique that is part of the
java.io.ObjectOutputStream
and java.io.ObjectInputStream
protocol to
externalize the home and component references.
The container must be able to properly save and restore references to timers stored in the instance’s state even if the classes that implement the timers are not serializable.
If the session bean instance stores in its
conversational state an object reference to the
jakarta.ejb.SessionContext
interface, the container must be able to save
and restore the reference across the instance’s passivation. The
container can replace the original SessionContext
object with a
different and functionally equivalent SessionContext
object during
activation.
If the session bean instance stores in its
conversational state an object reference to the java:comp/env
JNDI
context or its subcontext, the container must be able to save and
restore the object reference across the instance’s passivation. The
container can replace the original object with a different and
functionally equivalent object during activation.
If the session
bean instance stores in its conversational state an object reference to
the UserTransaction
interface, the container must be able to save and
restore the object reference across the instance’s passivation. The
container can replace the original object with a different and
functionally equivalent object during activation.
If the session
bean instance stores in its conversational state an object reference to
a container-managed EntityManager
or to an EntityManagerFactory
obtained via injection or JNDI lookup, the container must be able to
save and restore the object reference across the instance’s passivation.
The container may destroy a session bean
instance if the instance does not meet the requirements for
serialization after PrePassivate
.
While the container is not required to use
the Serialization protocol for the Java programming language to store
the state of a passivated session instance, it must achieve the
equivalent result. The one exception is that containers are not required
to reset the value of transient
fields during
activation.[15] Declaring the session bean’s fields
as transient is, in general, discouraged.
4.2.2. The Effect of Transaction Rollback on Conversational State
A session object’s conversational state is not transactional. It is not automatically rolled back to its initial state if the transaction in which the object has participated rolls back.
If a rollback
could result in an inconsistency between a session object’s
conversational state and the state of the underlying database, the bean
developer (or the application development tools used by the developer)
must use the afterCompletion
notification to manually reset its state.
4.3. Protocol Between a Session Bean Instance and its Container
Containers themselves make no actual service demands on the session bean instances. The container makes calls on a bean instance to provide it with access to container services and to deliver notifications issued by the container.
4.3.1. Required Session Bean Metadata
A session bean must be annotated or denoted
in the deployment descriptor as a stateless, stateful, or singleton
session bean. A stateless session bean must be annotated with the
Stateless
annotation or denoted in the deployment descriptor as a
stateless session bean. A stateful session bean must be annotated with
the Stateful
annotation or denoted in the deployment descriptor as a
stateful session bean. A singleton session bean must be annotated with
the Singleton
annotation or denoted in the deployment descriptor as a
singleton session bean. The Stateful
, Singleton
, and Stateless
annotations are component-defining annotations and are applied to the
bean class.
4.3.2. Dependency Injection
A session bean may use dependency injection
mechanisms to acquire references to resources or other objects in its
environment (see Enterprise Bean Environment). If a session bean makes use of dependency
injection, the container injects these references after the bean instance
is created, and before any business methods are invoked on the bean
instance. If a dependency on the SessionContext
is declared, or if the
bean class implements the optional SessionBean
interface (see The SessionBean Interface),
the SessionContext
is also injected at this time. If dependency injection
fails, the bean instance is discarded.
4.3.3. The SessionContext Interface
If the bean
specifies a dependency on the SessionContext
interface (or if the bean
class implements the SessionBean
interface), the container must
provide the session bean instance with a SessionContext
object. This
gives the session bean instance access to the instance’s context
maintained by the container. The SessionContext
interface has the
following methods:
-
The
getCallerPrincipal
method returns thejava.security.Principal
that identifies the invoker. -
The
isCallerInRole
method tests if the session bean instance’s caller has a particular role. -
The
setRollbackOnly
method allows the instance to mark the current transaction such that the only outcome of the transaction is a rollback. Only instances of a session bean with container-managed transaction demarcation are permitted to use this method. -
The
getRollbackOnly
method allows the instance to test if the current transaction has been marked for rollback. Only instances of a session bean with container-managed transaction demarcation are permitted to use this method. -
The
getUserTransaction
method returns thejakarta.transaction.UserTransaction
interface. The instance can use this interface to demarcate transactions and to obtain transaction status. Only instances of a session bean with bean-managed transaction demarcation are permitted to use this method. -
The
getTimerService
method returns thejakarta.ejb.TimerService
interface. Only stateless session beans and singleton session beans are permitted to use this method. Stateful session beans cannot be timed objects. -
The
getBusinessObject(java.lang.Class<T> businessInterface)
method returns a business object reference to the session bean’s business interface or no-interface view. In the case of the no-interface view, the argument is of the type of the bean class. Only session beans with an Enterprise Beans 3.x business interface or no-interface view are permitted to call this method.
If a subsequent invocation is made on the result ofgetBusinessObject
, then:-
For a stateless session bean, the invocation will be delivered to another stateless session bean instance.
-
For a stateful session bean or singleton session bean, the invocation will be delivered to the bean instance that returned the reference. The existing rules regarding reentrancy would then apply.
-
-
The
getInvokedBusinessInterface
method returns the session bean business interface or no-interface view (bean class) type through which the bean was invoked. -
The
getEJBObject
method returns the session bean’s remote component interface. Only session beans with a remote EJBObject interface are permitted to call this method. -
The
getEJBHome
method returns the session bean’s remote home interface. Only session beans with a remote home interface are permitted to call this method. -
The
getEJBLocalObject
method returns the session bean’s local component interface. Only session beans with a localEJBLocalObject
interface are permitted to call this method. -
The
getEJBLocalHome
method returns the session bean’s local home interface. Only session beans with a local home interface are permitted to call this method. -
The
lookup
method enables the session bean to look up its environment entries in the JNDI naming context. -
The
wasCancelCalled
method enables an asynchronous session bean method to check whether the client invoked itsFuture.cancel
method. TheSessionContext.wasCancelCalled
method only returns true if the cancel method was invoked on the clientFuture
object corresponding to the currently executing business method and themayInterruptIfRunning
parameter was set to true. -
The
getContextData
method enables a business method, lifecycle callback method, or timeout method to retrieve or update the interceptor and/or webservices context data associated with its invocation.
4.3.3.1. Use of the MessageContext Interface by Session Beans
A session bean that implements a web service
endpoint using the Jakarta XML Web Services contracts should use the
WebServiceContext
, which can be injected by use of the Resource
annotation. The WebServiceContext
interface allows the session bean
instance to see the SOAP message for the web service endpoint, as well
as the properties set by the Jakarta XML Web Services message handlers, if any. The
session bean may use the WebServiceContext
interface to set properties
for the Jakarta XML Web Services message handlers, if any. See [4].
The jakarta.xml.ws.handler.MessageContext
[4] is also
accessible to interceptors for session bean web service endpoints. See
InvocationContext.
4.3.4. Session Bean Lifecycle Callback Interceptor Methods
The following lifecycle event callbacks are
supported for session beans. With the exception of AroundConstruct
lifecycle callback interceptors (see [15]), all
interceptor methods may be defined directly on the bean class or on a
separate interceptor class. See Lifecycle Callback Interceptor Methods and Interceptors.
-
AroundConstruct
-
PostConstruct
-
PreDestroy
-
PostActivate
-
PrePassivate
The PostConstruct
callback invocations
occur before the first business method invocation on the bean instance.
This is at a point after which any dependency injection has been
performed by the container.
The PostConstruct
lifecycle callback
interceptor methods execute in an unspecified security context.
The PostConstruct
lifecycle callback
interceptor methods for a stateless session bean execute in an
unspecified transaction context. The PostConstruct
lifecycle callback
interceptor methods for a singleton session bean execute in a
transaction context determined by the bean’s transaction management type
and any applicable transaction attribute. The PostConstruct
lifecycle
callback interceptor methods for a stateful session bean execute in a
transaction context determined by the lifecycle callback method’s
transaction attribute.
The PreDestroy
callback notification
signals that the instance is in the process of being removed by the
container. In the PreDestroy
lifecycle callback interceptor methods,
the instance typically releases the resources that it has been holding.
The PreDestroy
lifecycle callback
interceptor methods execute in an unspecified security context.
The PreDestroy
lifecycle callback interceptor
methods for a stateless session bean execute in an unspecified
transaction context. The PreDestroy
lifecycle callback interceptor
methods for a singleton session bean execute in a transaction context
determined by the bean’s transaction management type and any applicable
transaction attribute. The PreDestroy
lifecycle callback interceptor
methods for a stateful bean execute in a transaction context determined
by the lifecycle callback method’s transaction attribute.
The PrePassivate
and PostActivate
lifecycle callback interceptor methods are only called on a stateful
session bean instance if the bean is passivation capable. By default a
stateful session bean is passivation capable. See Disabling Passivation of Stateful Session Beans on how to
disable passivation of a stateful session bean.
The PrePassivate
callback notification
signals the intent of the container to passivate the instance. The
PostActivate
notification signals the instance it has just been
reactivated. Because containers automatically maintain the
conversational state of a stateful session bean instance when it is
passivated, these notifications are not needed for most session beans.
Their purpose is to allow stateful session beans to maintain those open
resources that need to be closed prior to an instance’s passivation and
then reopened during an instance’s activation.
The PrePassivate
and PostActivate
lifecycle callback interceptor methods execute in an unspecified
security context.
The PrePassivate
and PostActivate
lifecycle callback interceptor methods execute in a transaction context
determined by the lifecycle callback method’s transaction attribute.
4.3.5. The SessionBean Interface
The session bean class is not required to
implement the SessionBean
interface or the Serializable
interface.
Interceptor classes for the bean are likewise not required to implement
the Serializable
interface.
Compatibility Note: The SessionBean interface was required to be implemented by the session bean class in earlier versions of the Enterprise Beans specification. Under the Enterprise Beans 3.x API, the functionality previously provided by the SessionBean interface is available to the bean class through selective use of dependency injection (of the SessionContext) and optional lifecycle callback interceptor methods.
The SessionBean
interface defines four
methods: setSessionContext
, ejbRemove
, ejbPassivate
, and
ejbActivate
.
The setSessionContext
method is called by the bean’s container to
associate a session bean instance with its context maintained by the
container. Typically a session bean instance retains its session context
as part of its state.
The ejbRemove
notification signals that the
instance is in the process of being removed by the container. In the
ejbRemove
method, the instance typically releases the same resources
that it releases in the ejbPassivate
method.
The ejbPassivate
notification signals the
intent of the container to passivate the instance. The ejbActivate
notification signals the instance it has just been reactivated. Their
purpose is to allow stateful session beans to maintain those open
resources that need to be closed prior to an instance’s passivation and
then reopened during an instance’s activation. The ejbPassivate
and
ejbActivate
methods are only called on stateful session bean
instances.
This specification requires that the
ejbRemove
, ejbActivate
, and ejbPassivate
methods of the
SessionBean
interface, and the ejbCreate
method of a stateless
session bean be treated as PreDestroy
, PostActivate
,
PrePassivate
and PostConstruct
life cycle callback interceptor
methods, respectively.
If the session bean implements the
SessionBean
interface, the PreDestroy
annotation on the bean class
can only be applied to the ejbRemove
method; the PostActivate
annotation can only be applied to the ejbActivate
method; the
PrePassivate
annotation can only be applied to the ejbPassivate
method. Similar requirements apply to use of deployment descriptor
metadata as an alternative to the use of annotations.
4.3.6. The Session Synchronization Notifications for Stateful Session Beans
A stateful
session bean class can optionally implement the
jakarta.ejb.SessionSynchronization
interface or annotate methods using the
individual AfterBegin
, BeforeCompletion
, and AfterCompletion
annotations. The deployment descriptor may also be used to declare the
individual session synchronization methods. These provide the session
bean instances with transaction
synchronization notifications. The instances can use these
notifications, for example, to manage database data they may cache
within transactions—e.g., if Jakarta Persistence is not used. A
stateful session bean class may use either the
jakarta.ejb.SessionSynchronization
interface or the session
synchronization annotations, but not both. If annotation are used, there
must be at most one AfterBegin
method, one BeforeCompletion
method,
and one AfterCompletion
method for the bean.
The afterBegin
notification signals a session bean instance that a new transaction has
begun. The container invokes this method before the first business
method within a transaction (which is not necessarily at the beginning
of the transaction). The afterBegin
notification is invoked with the
transaction context. The instance may do any database work it requires
within the scope of the transaction.
The beforeCompletion
notification is issued when a session bean
instance’s client has completed work on its current transaction but
prior to committing the resource managers used by the instance. At this
time, the instance should write out any database updates it has cached.
The instance can cause the transaction to roll back by invoking the
setRollbackOnly
method on its
SessionContext
object.
The afterCompletion
notification signals that the current
transaction has completed. A completion status of true
indicates that
the transaction has committed. A status of false
indicates that a
rollback has occurred. Since a session bean instance’s conversational
state is not transactional, it may need to manually reset its state if a
rollback occurred.
All Container Providers must support the
session synchronization notifications. If a
bean class implements the SessionSynchronization
interface, the
container must invoke the afterBegin
, beforeCompletion
, and
afterCompletion
notifications as required by the specification. If the
bean implementor uses the session synchronization annotations, the
container must invoke only the notifications corresponding to the
annotations that have been used.
If a stateful session bean’s PostConstruct
,
PreDestroy
, PrePassivate
or PostActivate
lifecycle callback interceptor
method is invoked in the scope of a transaction, session synchronization
callbacks for the transaction are not called on the bean instance.
A session synchronization method can have
public
, private
, protected
, or package
level access. A session
synchronization method must not be declared as final
or static
.
Only a stateful session bean with
container-managed transaction demarcation can receive session
synchronization notifications. Stateless session beans and singleton
session beans must not implement the SessionSynchronization
interface
or use the session synchronization annotations.
There is no need for a session bean with bean-managed transaction demarcation to rely on the synchronization call backs because the bean is in control of the commit—the bean knows when the transaction is about to be committed and it knows the outcome of the transaction commit.
4.3.7. Timeout Callbacks for Stateless and Singleton Session Beans
A stateless session bean or singleton session bean can be registered with the Enterprise Beans Timer Service for time-based event notifications. The container invokes the appropriate bean instance timeout callback method when a timer for the bean has expired. See Timer Service. Stateful session beans cannot be registered with the Enterprise Beans Timer Service, and therefore should not implement timeout callback methods.
4.3.8. Business Method Delegation
The session bean’s business interface, no-interface view, component interface, or web service endpoint defines the business methods callable by a client.
4.3.9. Session Bean Creation
Except as noted below, the container creates
an instance of a session bean as follows. First, the container calls the
bean class constructor to create a new session bean instance. Second,
the container performs any dependency injection as specified by metadata
annotations on the bean class or by the deployment descriptor. This
includes the bean’s SessionContext
, if applicable. Third, the container
calls the PostConstruct
lifecycle callback interceptor methods for the
bean, if any. The additional steps described below in Stateful Session Beans
and Stateless Session Beans apply if the session bean is invoked through the Enterprise Beans 2.1
client view APIs.
If an interceptor associated with the session
bean declares an AroundConstruct
lifecycle callback interceptor
method, the container follows the rules for the AroundConstruct
interceptors defined in the Jakarta® Interceptors specification [15].
4.3.9.1. Stateful Session Beans
If the bean is a stateful session bean and
the client has used one of the create<METHOD>
methods defined in the
session bean’s home or local home interface to create the bean, the
container then calls the instance’s initialization method whose
signature matches the signature of the create<METHOD>
invoked by the
client, passing to the method the input parameters sent from the client.
If the bean class is written to the Enterprise Beans 3.x API, and has been adapted
for use with an earlier client view, this initialization method is a
matching Init
method, as designated by use of the Init
annotation,
or init-method
deployment descriptor element.[16]
If the bean class was written to the Enterprise Beans 2.1 or earlier API, this
initialization method is a matching ejbCreate<METHOD>
method, as
described in ejbCreate<METHOD> Methods.
Each stateful session bean class that has a home interface must have at least one such initialization method. The number and signatures of a session bean’s initialization methods are specific to each session bean class. Since a stateful session bean represents a specific, private conversation between the bean and its client, its initialization parameters typically contain the information the client uses to customize the bean instance for its use.
4.3.9.2. Stateless Session Beans
A stateless session bean that has an Enterprise Beans 2.1
local or remote client view has a single create
method on its home
interface. In this case, Enterprise Beans 2.1 required the stateless session bean
class to have a single no-arg ejbCreate
method. Under the Enterprise Beans 3.x API,
it is not required that a stateless session bean have an ejbCreate
method, even when it has a home interface. An Enterprise Beans 3.x stateless session
bean class may have a PostConstruct
method, as described in Session Bean Lifecycle Callback Interceptor Methods.
If the stateless session bean instance has an
ejbCreate
method, the container treats the ejbCreate
method as the
instance’s PostConstruct
method, and, in this case, the
PostConstruct
annotation (or deployment descriptor metadata) can only
be applied to the bean’s ejbCreate
method.
A stateless session bean that provides only a
web service client view has no create
method. If the ejbCreate
method required by Enterprise Beans 2.1 is present, it is treated by the container as
the instance’s PostConstruct
method, and is invoked when the container
needs to create a new session bean instance in order to service a client
request.
4.3.10. Stateful Session Bean Removal
A stateful session bean written to the Enterprise Beans
3.x API typically has one or more remove methods designated by means of
the Remove
annotation or remove-method
deployment descriptor
element.[17]
Invocation of the remove method causes
the removal of the stateful session bean after the remove method
successfully completes. If the Remove
annotation specifies the value
of retainIfException
as true
and the invocation of the Remove
method throws an application exception, the instance is not removed. The
retain-if-exception
subelement of the remove-method
deployment
descriptor element may be explicitly specified to override the
retainIfException
value specified or defaulted by the Remove
annotation. The default value of the retainIfException
element is
false
. If there are multiple remove methods, their
retainIfException
values can differ.
4.3.11. Stateful Session Bean Timeout
A Bean Provider or Deployer may optionally
assign a timeout value to a stateful session bean. The stateful session
bean timeout is specified using the StatefulTimeout
annotation on the
bean class. It may also be specified using the stateful-timeout
deployment descriptor element. If both are specified, the deployment
descriptor value overrides that of the annotation.
The timeout value is the amount of time a stateful session bean instance is permitted to remain idle (not receive any client invocations) before being removed by the container. A timeout value of -1 indicates that the bean must not be removed due to timeout for as long as the application is deployed. A timeout value of 0 indicates that the bean is immediately eligible for removal after becoming idle.
If a stateful session bean timeout is not designated using this standard metadata, the container determines when to end the lifetime of the bean, possibly based on vendor-specific configuration. The details of such configuration are beyond the scope of the specification.
A stateful session bean instance must not be removed due to timeout while it is associated with a transaction or while it is processing a business method or callback. The full stateful session bean life cycle is covered in Stateful Session Beans.
4.3.12. Business Method Interceptor Methods for Session Beans
The AroundInvoke
interceptor methods are
supported for session beans. These interceptor methods may be defined on
the bean class and/or on interceptor classes, and apply to the handling
of the invocation of the business methods of the bean’s business
interface, no-interface view, component interface, and/or web service
endpoint.
For stateful session beans that use the
session synchronization notifications, the afterBegin
notification
occurs before any AroundInvoke
method invocations, and the
beforeCompletion
notification occurs after all AroundInvoke
invocations have finished.
Interceptors are described in Interceptors.
4.3.13. Serializing Session Bean Methods
The following requirements apply to stateless and stateful session beans. See Singleton Session Bean Concurrency for singleton session bean concurrency requirements.
The container serializes calls to each stateful and stateless session bean instance. Most containers will support many instances of a session bean executing concurrently; however, each instance sees only a serialized sequence of method calls. Therefore, a stateful or stateless session bean does not have to be coded as reentrant.
The container must serialize all the
container-invoked callbacks (that is, the
business method interceptor methods, lifecycle callback interceptor
methods, timeout callback methods, beforeCompletion
methods, and so on),
and it must serialize these callbacks with the client-invoked business
method calls.
By default, clients are allowed to make concurrent calls to a stateful session object and the container is required to serialize such concurrent requests. Note that the container never permits multi-threaded access to the actual stateful session bean instance. For this reason, Read/Write method locking metadata, as well as the bean-managed concurrency mode, are not applicable to stateful session beans and must not be used.[18] See Singleton Session Bean Concurrency for a description of how these concurrency modes and locking types apply to singleton session beans.
The Bean Provider may optionally specify that
concurrent client requests to a stateful session bean are prohibited.
This is done using the AccessTimeout
annotation or the access-timeout
deployment descriptor element with a value of 0
. In this case, if a
client-invoked business method is in progress on an instance when
another client-invoked call, from the same or different client, arrives
at the same stateful session bean istance, if the second client is a
client of the bean’s business interface or no-interface view, the
concurrent invocation must result in the second client receiving the
jakarta.ejb.ConcurrentAccessException
.[19] If the
Enterprise Beans 2.1 client view is used, the container must throw the
java.rmi.RemoteException
if the second client is a remote client, or the
jakarta.ejb.EJBException
if the second client is a local client.
There is no need for any restrictions against concurrent client access to stateless session beans because the container routes each request to a different instance of the stateless session bean class.
4.3.13.1. Stateful Session Bean Concurrent Access Timeouts
The AccessTimeout
annotation is used to
specify the amount of time a stateful session bean request should block
in the case that it cannot immediately access a bean instance that is
already processing a different request. If an access attempt times out,
the container throws the jakarta.ejb.ConcurrentAccessTimeoutException
to
the client.
The AccessTimeout
annotation can be specified
on a business method or on the bean class (or superclass). The
AccessTimeout
annotation specified on a class applies the access timeout
to all business methods of that class. If the AccessTimeout
annotation
is specified on both the class and on a business method of that class,
the method-level annotation takes precedence.
An AccessTimeout
value of -1
indicates that a
concurrent client request will block indefinitely until it can proceed.
4.3.14. Transaction Context of Session Bean Methods
The following session bean methods are invoked in the scope of a transaction determined by the transaction attribute specified in the bean’s metadata annotations or deployment descriptor.
-
An implementation of a method defined in a session bean’s business interface or component interface or no-interface view.
-
A web service method.
-
A timeout callback method
-
A singleton session bean’s
PostConstruct
orPreDestroy
lifecycle callback interceptor method.
A stateful session bean’s PostConstruct
,
PreDestroy
, PrePassivate
or PostActivate
lifecycle callback interceptor
method is invoked in the scope of a transaction determined by the
transaction attribute specified in the lifecycle callback method’s
metadata annotations or deployment descriptor.
A stateful session bean’s afterBegin
and
beforeCompletion
methods are always called with the same transaction
context as the business methods executed between the afterBegin
and
beforeCompletion
methods.
A session bean’s constructor, setSessionContext
, other dependency
injection methods, other life cycle callback interceptor methods, and
afterCompletion
methods are called with an unspecified transaction context.
Refer to Handling of Methods that Run with "an unspecified transaction context" for how the container executes methods with an unspecified
transaction context.
If database operations are performed within a
stateful session bean’s PostConstruct
, PreDestroy
, PrePassivate
or PostActivate
lifecycle callback interceptor methods these
operations will not be part of the client’s transaction. If such a
transaction is rolled back, the instance is discarded. See Dealing with Exceptions for
rules on dealing with exceptions in stateful session beans.
4.4. Access in the Global JNDI Namespace
The Jakarta EE Platform Specification defines a standardized global JNDI namespace and a series of related namespaces that map to the various scopes of a Jakarta EE application. These namespaces can be used by applications to portably retrieve references to components and resources. This specification defines the JNDI names by which session beans are required to be registered within these namespaces.
4.4.1. Syntax
Each portable session bean global JNDI name has the following syntax:
java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
-
<app-name>
only applies if the session bean is packaged within an.ear
file. It defaults to the base name of the.ear
file with no filename extension, unless specified by theapplication.xml
deployment descriptor. -
<module-name>
is the name of the module in which the session bean is packaged. In a stand-alone ejb-jar file or.war
file,<module-name>
defaults to the base name of the module with any filename extension removed. In an ear file, the<module-name>
defaults to the pathname of the module with any filename extension removed, but with any directory names included. The default module name can be overridden using the module-name element ofejb-jar.xml
file (forejb-jar
files) orweb.xml
file (for.war
files). -
<bean-name>
is the ejb-name of the enterprise bean. For enterprise beans defined via annotations, it defaults to the unqualified name of the session bean class, unless otherwise specified by thename
element of theStateless
,Stateful
, orSingleton
annotation. For enterprise beans defined via theejb-jar.xml
file, it is specified in theejb-name
deployment descriptor element.
The container registers a separate JNDI name entry for each local business interface, each remote business interface, any no-interface view, any local home interface, and any remote home interface. For the no-interface view, the last portion of the entry name is the fully-qualified name of the bean class.
In addition to the previous requirements, if the bean exposes only one of the applicable client interfaces (or, alternatively has only a no-interface view), the container registers an entry for that view with the following syntax:
java:global[/<app-name>]/<module-name>/<bean-name>
The container is also required to make
session bean JNDI names available through the java:app
and java:module
namespaces.[20]
4.4.1.1. java:app
The java:app
prefix allows a component
executing within a Jakarta EE application to access an application-specific
namespace. The resulting syntax is:
java:app/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
Note that <module-name>
is a required part of
the syntax, even for names based on session bean components packaged
within a stand-alone module.
4.4.2. Examples
The following examples show the resulting global JNDI names for various session beans.
4.4.2.1. Session bean exposing a single local business interface
package com.acme;
@Stateless
public class FooBean implements Foo { ... }
If FooBean
is packaged in fooejb.jar
without
a deployment descriptor and deployed as a stand-alone module, the
resulting JNDI name entries are:
java:global/fooejb/FooBean
java:global/fooejb/FooBean!com.acme.Foo
java:app/fooejb/FooBean
java:app/fooejb/FooBean!com.acme.Foo
java:module/FooBean
java:module/FooBean!com.acme.Foo
If FooBean
is packaged in fooejb.jar
within
fooapp.ear
, without the use of any deployment descriptors, the resulting
global JNDI name entries are:
java:global/fooapp/fooejb/FooBean
java:global/fooapp/fooejb/FooBean!com.acme.Foo
java:app/fooejb/FooBean
java:app/fooejb/FooBean!com.acme.Foo
java:module/FooBean
java:module/FooBean!com.acme.Foo
If FooBean
is packaged in a stand-alone
fooweb.war
file, without the use of any deployment descriptors, the
resulting global JNDI name entries are:
java:global/fooweb/FooBean
java:global/fooweb/FooBean!com.acme.Foo
java:app/fooweb/FooBean
java:app/fooweb/FooBean!com.acme.Foo
java:module/FooBean
java:module/FooBean!com.acme.Foo
If FooBean
is packaged in fooweb.war
within
fooapp.ear
, without the use of any deployment descriptors, the resulting
global JNDI name entries are:
java:global/fooapp/fooweb/FooBean
java:global/fooapp/fooweb/FooBean!com.acme.Foo
java:app/fooweb/FooBean
java:app/fooweb/FooBean!com.acme.Foo
java:module/FooBean
java:module/FooBean!com.acme.Foo
4.4.2.2. Session bean exposing multiple client views
package com.acme;
@Singleton(name="Shared")
@LocalBean
@Remote(com.acme.SharedRemote.class)
public class SharedBean { ... }
If SharedBean
is packaged in shared.jar
without a deployment descriptor and deployed as a stand-alone module,
the resulting global JNDI name entries are:
java:global/shared/Shared!com.acme.SharedBean
java:global/shared/Shared!com.acme.SharedRemote
java:app/shared/Shared!com.acme.SharedBean
java:app/shared/Shared!com.acme.SharedRemote
java:module/Shared!com.acme.SharedBean
java:module/Shared!com.acme.SharedRemote
4.5. Asynchronous Methods
A session bean can expose methods with asynchronous client invocation semantics. For asynchronous invocations, control returns to the client before the container dispatches the invocation to a bean instance. An asynchronous method is a business method exposed through one or more of the remote business, local business, or no-interface session bean views.
Asynchronous methods can return a Future<V>
object that allows the client to retrieve a result value, check for
exceptions, or attempt to cancel an in-progress invocation.
4.5.1. Metadata
The Asynchronous
annotation is used to
designate which business methods are asynchronous.
The Asynchronous
annotation can be applied to
a particular business method of a bean class (or superclass), or to the
bean class (or superclass). If the Asynchronous
annotation is applied at
the class level, all business methods declared on that specific class
are asynchronous.
Asynchronous
methods can also be designated
via the deployment descriptor.
Asynchronous
method invocation semantics only
apply to the no-interface, local business, and remote business client
views. Support for asynchronous business methods exposed through the
local component, remote component, and web service client views is not
required by this specification, and applications which expose such views
with asynchronous methods will not be portable.
4.5.2. Method Requirements
The valid return type of an asynchronous
method is either void or java.util.concurrent.Future<V>
, where V
is the
result value type.
An asynchronous method with return type void
must not declare any application exceptions. An asynchronous method with
return type Future<V>
is permitted to declare application exceptions.
4.5.2.1. Return Values
The Bean Provider makes the result value of
an asynchronous invocation available to the client by returning a
Future<V>
object for which both get()
methods return the result value. A
concrete Future<V>
implemention called jakarta.ejb.AsyncResult<V>
is
provided by the container as a convenience. The AsyncResult<V>
class has
a constructor that takes the result value as a parameter.
Example:
@Asynchronous
public Future<Integer> performCalculation(...) {
// ... do calculation
Integer result = ...;
return new AsyncResult<Integer>(result);
}
Note that the Future<V>
object returned from
the bean class method (including any instance of AsyncResult<V>
) is only
used as a way to pass the result value to the container. This object is
not given directly to the caller, since by definition the caller already
has a container-generated Future<V>
object that was returned from the
original invocation.
4.5.2.2. Method cancellation
A client can request that an asynchronous
invocation be cancelled by calling the
Future<V>.cancel(boolean mayInterruptIfRunning)
method.
The Bean Provider can check whether the
client has requested cancellation by calling the
SessionContext.wasCancelCalled()
method within the context of the
asynchronous method. See Asynchronous Invocations for the description of the client Future contract.
4.5.3. Transactions
The client’s transaction context does not
propagate with an asynchronous method invocation. From the Bean
Provider’s point of view, there is never a transaction context flowing
in from the client. This means, for example, that the semantics of the
REQUIRED
transaction attribute on an asynchronous method are exactly the
same as REQUIRES_NEW
.
4.5.4. Security
The caller security principal propagates with an asynchronous method invocation. Caller security principal propagation behaves exactly the same for asynchronous method invocations as it does for synchronous session bean invocations.
4.5.5. Client Exception Behavior
Client exception behavior depends on whether
the asynchronous method has return type void or Future<V>
.
If the asynchronous method has return type
void
, then once control has returned from the client’s method call no
exceptions occurring during the processing of the invocation will be
delivered to the client. For this reason, asynchronous methods with
return type void
must not declare application exceptions.
If the asynchronous method has return type
Future<V>
, an exception thrown from the processing of the asynchronous
method invocation is accessible to the client via the getCause()
method
of a java.util.concurrent.ExecutionException
thrown from either
Future.get()
method.
4.6. Stateful Session Beans
4.6.1. Stateful Session Bean Lifecycle State Diagram
The following figure illustrates the life cycle of a stateful session bean instance.
The following steps describe the life cycle of a stateful session bean instance:
-
A session bean instance’s life starts when a client obtains a reference to a stateful session bean instance through dependency injection or JNDI lookup, or when the client invokes a
create<METHOD>
method on the session bean’s home interface. This causes the container to invoke the session bean class constructor to create a new session bean instance.[21] Next, the container performs any dependency injection as specified by metadata annotations on the bean class or by the deployment descriptor. The container then calls thePostConstruct
lifecycle callback interceptor method(s) for the bean, if any. Finally, if the session bean was written to the Enterprise Beans 2.1 client view, the container invokes the matchingejbCreate<METHOD>
orInit
method on the instance. The container then returns the session object reference to the client. The instance is now in the method ready state.
NOTE: When a stateful session bean is looked up or otherwise obtained through the explicit JNDI lookup mechanisms, the container must provide a new stateful session bean instance, as required by the Jakarta EE specification (Section "Java Naming and Directory Interface (JNDI) Naming Context" [14]). -
The session bean instance is now ready for client’s business methods. Based on the transaction attributes in the session bean’s metadata annotations and/or deployment descriptor and the transaction context associated with the client’s invocation, a business method is executed either in a transaction context or with an unspecified transaction context (shown as "tx method" and "non-tx method" in the diagram). See Support for Transactions for how the container deals with transactions.
-
A non-transactional method is executed while the instance is in the method ready state.
-
An invocation of a transactional method causes the instance to be included in a transaction. When the session bean instance is included in a transaction, the container issues the
afterBegin
method on it if the session bean has anafterBegin
callback method.[22] TheafterBegin
method is invoked on the instance before any business method or business method interceptor method is executed as part of the transaction. The instance becomes associated with the transaction and will remain associated with the transaction until the transaction completes. -
Session bean methods invoked by the client in this transaction can now be delegated to the bean instance. An error occurs if a client attempts to invoke a method on the session object and the bean’s metadata annotations and/or deployment descriptor for the method requires that the container invoke the method in a different transaction context than the one with which the instance is currently associated or in an unspecified transaction context.
-
If a transaction commit has been requested, the transaction service notifies the container of the commit request before actually committing the transaction, and the container issues the
beforeCompletion
callback on the instance if the session bean has abeforeCompletion
callback method.[22] WhenbeforeCompletion
is invoked, the instance should write any cached updates to the database.[23] If a transaction rollback had been requested instead, the rollback status is reached without the container issuing abeforeCompletion
. The container may not call thebeforeCompletion
method if the transaction has been marked for rollback (nor does the instance write any cached updates to the database). -
The transaction service then attempts to commit the transaction, resulting in either a commit or rollback.
-
When the transaction completes, the container issues
afterCompletion
on the instance if the session bean has anafterCompletion
callback method,[22] specifying the status of the completion (either commit or rollback). If a rollback occurred, the bean instance may need to reset its conversational state back to the value it had at the beginning of the transaction. -
The container’s caching algorithm may decide that the bean instance should be evicted from memory. (This could be done at the end of each method, or by using an LRU policy). The container invokes the
PrePassivate
lifecycle callback interceptor method(s) for the bean instance, if any. After this completes, the container saves the instance’s state to secondary storage. A session bean can be passivated only between transactions, and not within a transaction. -
While the instance is in the passivated state, the container may remove the session object after the expiration of a timeout specified by the Deployer. All object references and handles for the session object become invalid. If a client attempts to invoke a method on the bean’s business interface, the container will throw the
jakarta.ejb.NoSuchEJBException
.[24] If the Enterprise Beans 2.1 client view is used, the container will throw thejava.rmi.NoSuchObjectException
if the client is a remote client, or thejakarta.ejb.NoSuchObjectLocalException
if the client is a local client. -
If a client invokes a session object whose session bean instance has been passivated, the container will activate the instance. To activate the session bean instance, the container restores the instance’s state from secondary storage and invokes the
PostActivate
method for the instance, if any. -
The session bean instance is again ready for client methods.
-
When the client calls a business method of the bean that has been designated as a
Remove
method on the bean class or aremove
method on the home or component interface, the container invokesPreDestroy
lifecycle callback interceptor methods, if any, for the bean instance after theRemove
method completes.[25] This ends the life of the session bean instance and the associated session object. If a client subsequently attempts to invoke a method on the bean’s business interface, the container will throw thejakarta.ejb.NoSuchEJBException
.[26] If the Enterprise Beans 2.1 client view is used, any subsequent attempt causes thejava.rmi.NoSuchObjectException
to be thrown if the client is a remote client, or thejakarta.ejb.NoSuchObjectLocalException
if the client is a local client. (Thejava.rmi.NoSuchObjectException
is a subclass of thejava.rmi.RemoteException
; thejakarta.ejb.NoSuchObjectLocalException
is a subclass of thejakarta.ejb.EJBException
). If theRemove
method completes successfully or if theRemove
method throws an application exception for whichretainIfException
is nottrue
or if a system exception is thrown, session synchronization methods are not called on the bean instance. If an application exception is thrown for whichretainIfException
istrue
, the bean is neither destroyed nor discarded, and session synchronization methods, if any, are called on the instance at the end of transaction. A container can also invoke thePreDestroy
method on the instance without a client call to remove the session object:-
After the lifetime of the Enterprise Beans object has expired
-
When the CDI context, to which the Enterprise Beans object belongs to, is destroyed.
-
The container must call the afterBegin
,
beforeCompletion
, and afterCompletion
methods if the session bean class
implements, directly or indirectly, the SessionSynchronization
interface, or if the bean class uses the session synchronization
annotations.
4.6.2. Operations Allowed in the Methods of a Stateful Session Bean Class
Operations Allowed in the Methods of a Stateful Session Bean defines
the methods of a stateful session bean class from which the session bean
instances can access the methods of the jakarta.ejb.SessionContext
interface, the java:comp/env
environment naming context, resource
managers, Timer
methods, the EntityManager
and
EntityManagerFactory
methods, and other enterprise beans.
If a session bean
instance attempts to invoke a method of the SessionContext
interface,
and that access is not allowed in Operations Allowed in the Methods of a Stateful Session Bean, the
container must throw the java.lang.IllegalStateException
.
If a session bean instance attempts to access a resource manager, an enterprise bean, an entity manager or entity manager factory, and that access is not allowed in Operations Allowed in the Methods of a Stateful Session Bean, the behavior is undefined by the Enterprise Beans architecture.
If a session bean instance attempts to invoke
a method of the Timer
interface and the access is not allowed in Operations Allowed in the Methods of a Stateful Session Bean,
the container must throw the java.lang.IllegalStateException
.
Bean method | Bean method can perform the following operations | |
---|---|---|
Container-managed transaction demarcation |
Bean-managed transaction demarcation |
|
constructor |
- |
- |
dependency injection methods (e.g., setSessionContext) |
JNDI access to java:comp/env |
JNDI access to java:comp/env |
PostConstruct, PreDestroy, PrePassivate, PostActivate lifecycle callback interceptor methods Note A |
JNDI access to java:comp/env |
UserTransaction methods |
business method from business interface or from no-interface view or from component interface; business method interceptor method |
JNDI access to java:comp/env |
UserTransaction methods |
afterBegin |
JNDI access to java:comp/env |
N/A (a bean with bean-managed transaction demarcation cannot implement the SessionSynchronization interface or use the session synchronization annotations) |
afterCompletion |
JNDI access to java:comp/env |
Notes:
[A] If a client calls lifecycle callback method
through a business interface or a no-interface view, the method is
treated like a business method.
Notes:
-
The
PostConstruct
,PreDestroy
,PrePassivate
,PostActivate
, and/orejbCreate<METHOD>
,ejbRemove
,ejbPassivate
, andejbActivate
methods of a stateful session bean with container-managed transaction demarcation are invoked in the scope of a transaction determined by the transaction attribute specified in the bean’s metadata annotations or deployment descriptor. -
The
Init
methods of a session bean with container-managed transaction demarcation execute with an unspecified transaction context. Refer to Handling of Methods that Run with "an unspecified transaction context" for how the container executes methods with an unspecified transaction context. -
In some cases, lifecycle callback interceptor methods initiated solely by the container without an associated client invocation run in an unspecified security context, e.g., a
PostConstruct
method callback invoked as a side-effect of the injection of a remote or local business interface reference. However, the container is still required to permit client calls to these methods according to the rules in this table (see note).
Additional restrictions:
-
The getRollbackOnly and setRollbackOnly methods of the SessionContext interface should be used only in the session bean methods that execute in the context of a transaction. The container must throw the
java.lang.IllegalStateException
if the methods are invoked while the instance is not associated with a transaction.
The reasons for disallowing the operations in Operations Allowed in the Methods of a Stateful Session Bean follow:
-
Invoking the
getBusinessObject
method is disallowed if the session bean does not define a business interface or a no-interface view. -
Invoking the
getInvokedBusinessInterface
method is disallowed if the session bean does not define a business interface or a no-interface view. It is also disallowed if the current business method was not invoked through a business interface or the no-interface view. -
Invoking the
getEJBObject
andgetEJBHome
methods is disallowed if the session bean does not define a remote component client view. -
Invoking the
getEJBLocalObject
andgetEJBLocalHome
methods is disallowed if the session bean does not define a local component client view. -
Invoking the
getRollbackOnly
andsetRollbackOnly
methods is disallowed in the session bean methods for which the container does not have a meaningful transaction context, and to all session beans with bean-managed transaction demarcation. -
Accessing resource managers and enterprise beans is disallowed in the session bean methods for which the container does not have a meaningful transaction context and/or client security context.
-
The
UserTransaction
interface is unavailable to enterprise beans with container-managed transaction demarcation. -
The
TimerService
interface is unavailable to stateful session beans. -
Invoking the
getEJBObject
andgetEJBLocalObject
methods is disallowed in the session bean methods in which there is no session object identity established for the instance. -
Invoking the
wasCancelCalled
method is disallowed except when inside the context of the asynchronous methods that declareFuture<V>
object as the returning type.
4.6.3. Dealing with Exceptions
A RuntimeException that is not an application exception thrown from any method of the stateful session bean class (including the business methods and the lifecycle callback interceptor methods invoked by the container) results in the transition to the "does not exist" state. Exception handling is described in detail in Exception Handling. See the Jakarta Interceptors specification [15] for the rules pertaining to lifecycle callback interceptor methods when more than one such method applies to the bean class.
From the client perspective, the
corresponding session object does not exist any more. If a client
subsequently attempts to invoke a method on the bean’s business
interface or the no-interface view, the container will throw the
jakarta.ejb.NoSuchEJBException
.[27]
If the Enterprise Beans 2.1
client view is used, the container will throw the
java.rmi.NoSuchObjectException
if the client is a remote client, or the
jakarta.ejb.NoSuchObjectLocalException
if the client is a local client.
4.6.4. Missed PreDestroy
Calls
The Bean Provider
cannot assume that the container will always invoke the PreDestroy
lifecycle callback interceptor method(s) (or ejbRemove
method) for a
stateful session bean instance. The following scenarios result in the
PreDestroy lifecycle callback interceptor method(s) not being called for
an instance:
-
A crash of the Enterprise Beans container.
-
A system exception thrown from the instance’s method to the container.
-
A timeout of client inactivity while the instance is in the passive state. The timeout is specified by the Deployer in an Enterprise Beans container implementation-specific way.
If resources are allocated in a
PostConstruct
lifecycle callback interceptor method (or
ejbCreate<METHOD>
method) and/or in the business methods, and normally
released in a PreDestroy
lifecycle callback interceptor method, these
resources will not be automatically released in the above scenarios. The
application using the stateful session bean should provide some clean up
mechanism to periodically clean up the unreleased resources.
For example, if a shopping cart component is implemented as a session bean, and the session bean stores the shopping cart content in a database, the application should provide a program that runs periodically and removes “abandoned” shopping carts from the database.
4.6.5. Disabling Passivation of Stateful Session Beans
By default, the container may passivate a stateful session bean instance to a secondary storage to save resources. However, the Bean Provider can optionally configure the stateful session bean to prevent passivation of its instances.
For example, a stateful session bean instance may contain non-serializable attributes which would lead to runtime exceptions during passivation, or passivation and activation of such instances may cause degradation of application performance.
If the passivationCapable
element of the
Stateful
annotation is set to false or the passivation-capable
element
of the session deployment descriptor element is set to false
, the
container must not attempt to passivate instances of the bean.
Note: application server vendors may use passivation as a technique to provide high availability of stateful session beans by replicating their state from one JVM instance to another across which the container is distributed. In a failure situation, a stateful session bean is made available on a new JVM instance by what is commonly called stateful session bean failover. If a container implementation supports failover of stateful session beans using bean passivation, the failover capability for not passivation capable stateful session beans is not defined.
4.6.6. Transaction Semantics of Initialization, Destruction, Activation and Passivation
By default a stateful session bean’s
PostConstruct
, PreDestroy
, PrePassivate
and PostActivate
methods are executed in an unspecified transactional context. A
PostConstruct
, PreDestroy
, PrePassivate
and PostActivate
method of a stateful session bean with container-managed transaction
demarcation is permitted to have transaction attribute REQUIRES_NEW
or
NOT_SUPPORTED
(RequiresNew
or NotSupported
if the deployment descriptor
is used to specify the transaction attribute).
4.6.7. Restrictions for Transactions
The state diagram implies the following restrictions on transaction scoping of the client invoked business methods. The restrictions are enforced by the container and must be observed by the client programmer.
-
A stateful session bean instance can participate in at most a single transaction at a time.
-
If a stateful session bean instance is participating in a transaction, it is an error for a client to invoke a method on the session object such that the transaction attribute specified in the bean’s metadata annotations and/or the deployment descriptor would cause the container to execute the method in a different transaction context or in an unspecified transaction context. In such a case, the
jakarta.ejb.EJBException
will be thrown to a client of the bean’s business interface.[28] If the Enterprise Beans 2.1 client view is used, the container throws thejava.rmi.RemoteException
to the client if the client is a remote client, or thejakarta.ejb.EJBException
if the client is a local client.
If a stateful session bean instance is
participating in a transaction, it is an error for a client to invoke
the remove
method on the session object’s home or component interface
object. The container must detect such an attempt and throw the
jakarta.ejb.RemoveException
to the client. The container should not mark
the client’s transaction for rollback, thus allowing the client to
recover. Note that this restriction only applies to the remove method on
the session object’s home or component interface, not to the invocation
of Remove methods.
4.7. Stateless Session Beans
Stateless session beans are session beans whose instances have no conversational state. This means that all bean instances are equivalent when they are not involved in servicing a client-invoked method.
The term "stateless" signifies that an instance has no state for a specific client. However, the instance variables of the instance can contain the state across client-invoked method calls. Examples of such state include an open database connection and an object reference to an enterprise bean object.
Because all instances of a stateless session bean are equivalent, the container can choose to delegate a client-invoked method to any available instance. This means, for example, that the container may delegate the requests from the same client within the same transaction to different instances, and that the container may interleave requests from multiple transactions to the same instance.
A container only needs to retain the number of instances required to service the current client load. Due to client "think time", this number is typically much smaller than the number of active clients. Passivation is not needed or used for stateless session beans. The container creates another stateless session bean instance if one is needed to handle an increase in client work load. If a stateless session bean is not needed to handle the current client work load, the container can destroy it.
Because stateless session beans minimize the resources needed to support a large population of clients, depending on the implementation of the container, applications that use stateless session beans may scale somewhat better than those using stateful session beans. However, this benefit may be offset by the increased complexity of the client application that uses the stateless beans.
There is no fixed mapping between clients and stateless instances. The container simply delegates a client’s work to any available instance that is method-ready.
Compatability Note: Local and remote
clients using the Enterprise Beans 2.1 client view interfaces use the create
and
remove
methods on the home interface of a stateless session bean in the
same way as on a stateful session bean. To the Enterprise Beans 2.1 client, it
appears as if the client controls the life cycle of the session object.
However, the container handles the create
and remove
calls without
necessarily creating and removing an Enterprise Beans instance.
The home interface of a stateless session
bean must have one create method that takes no arguments. The create
method of the remote home interface must return the session bean’s
remote interface. The create
method of the local home interface must
return the session bean’s local interface.
There can be no other create
methods in the home interface.
A stateless session bean must not implement
the jakarta.ejb.SessionSynchronization
interface or use the session
synchronization annotations.
4.7.1. Stateless Session Bean Lifecycle State Diagram
When a client calls a method on a stateless session object or invokes a method on a stateless session bean through its web service client view, the container selects one of its method-ready instances and delegates the method invocation to it.
The following figure illustrates the life cycle of a stateless session bean instance.
The following steps describe the life cycle of a stateless session bean instance:
-
A stateless session bean instance’s life starts when the container invokes the session bean class constructor to create a new session bean instance.[29] Next, the container performs any dependency injection as specified by metadata annotations on the bean class or by the deployment descriptor. The container then calls the
PostConstruct
lifecycle callback interceptor methods for the bean, if any. The container can perform the instance creation at any time—there is no direct relationship to a client’s invocation of a business method or thecreate
method. -
The session bean instance is now ready to be delegated a business method call from any client or a call from the container to a timeout callback method.
-
When the container no longer needs the instance (usually when the container wants to reduce the number of instances in the method-ready pool), the container invokes the
PreDestroy
lifecycle callback interceptor methods for it, if any. This ends the life of the stateless session bean instance.
4.7.2. Operations Allowed in the Methods of a Stateless Session Bean Class
Operations Allowed in the Methods of a Stateless Session Bean defines
the methods of a stateless session bean class in which the session bean
instances can access the methods of the jakarta.ejb.SessionContext
interface, the java:comp/env
environment naming context, resource
managers, TimerService
and Timer
methods, the EntityManager
and
EntityManagerFactory
methods, and other enterprise beans.
If a session bean instance attempts to invoke
a method of the SessionContext
interface, and the access is not allowed
in Operations Allowed in the Methods of a Stateless Session Bean, the container must throw the
java.lang.IllegalStateException
.
If a session bean instance attempts to invoke
a method of the TimerService
or Timer
interface and the access is
not allowed in Operations Allowed in the Methods of a Stateless Session Bean, the container must throw
the java.lang.IllegalStateException
.
If a session bean instance attempts to access a resource manager, an enterprise bean, an entity manager or entity manager factory, and the access is not allowed in Operations Allowed in the Methods of a Stateless Session Bean, the behavior is undefined by the Enterprise Beans architecture.
Bean method | Bean method can perform the following operations | |
---|---|---|
Container-managed transaction demarcation |
Bean-managed transaction demarcation |
|
constructor |
- |
- |
dependency injectionmethods (e.g., setSessionContext) |
JNDI access to java:comp/env |
JNDI access to java:comp/env |
PostConstruct, PreDestroy lifecycle callback interceptor methods Note A |
JNDI access to java:comp/env |
JNDI access to java:comp/env |
business method from business interface or from no-interface view or from component interface; business method interceptor method |
JNDI access to java:comp/env |
UserTransaction methods |
business method from web service endpoint |
Message context methods |
UserTransaction methods |
timeout callback method |
JNDI access to java:comp/env |
UserTransaction methods |
Notes:
[A] If a client calls lifecycle
callback method through a business interface or a no-interface view,
the method is treated like a business method.
Additional restrictions:
-
The
getRollbackOnly
andsetRollbackOnly
methods of theSessionContext
interface should be used only in the session bean methods that execute in the context of a transaction. The container must throw thejava.lang.IllegalStateException
if the methods are invoked while the instance is not associated with a transaction.
The reasons for disallowing operations in Operations Allowed in the Methods of a Stateless Session Bean:
-
Invoking the
getBusinessObject
method is disallowed if the session bean does not define a business interface or a no-interface view. -
Invoking the
getInvokedBusinessInterface
method is disallowed if the session bean does not define a business interface or a no-interface view. It is also disallowed if the current business method was not invoked through a business interface or the no-interface view. -
Invoking the
getEJBObject
andgetEJBHome
methods is disallowed if the session bean does not define a remote component client view. -
Invoking the
getEJBLocalObject
andgetEJBLocalHome
methods is disallowed if the session bean does not define a local component client view. -
Invoking the
getRollbackOnly
andsetRollbackOnly
methods is disallowed in the session bean methods for which the container does not have a meaningful transaction context, and for all session beans with bean-managed transaction demarcation. -
Accessing resource managers, enterprise beans, and the EntityManager is disallowed in the session bean methods for which the container does not have a meaningful transaction context and/or client security context.
-
The
UserTransaction
interface is unavailable to session beans with container-managed transaction demarcation. -
Invoking the
wasCancelCalled
method is disallowed except when inside the context of the asynchronous methods that declare Future<V> object as the returning type.
4.7.3. Dealing with Exceptions
A RuntimeException
that is not an application exception thrown from any
method of the enterprise bean class (including the business methods and
the lifecycle callback interceptor methods invoked by the container)
results in the transition to the "does not exist" state. Exception
handling is described in detail in Exception Handling. See the
Jakarta Interceptors specification [15] for the
rules pertaining to lifecycle callback interceptor methods when more
than one such method applies to the bean class.
From the client perspective, the session object continues to exist. The client can continue accessing the session object because the container can delegate the client’s requests to another instance.
4.8. Singleton Session Beans
A singleton session bean is a session bean component that is instantiated once per application. In cases where the container is distributed over many virtual machines, each application will have one bean instance of the singleton for each JVM.
Once instantiated, a singleton session bean instance lives for the duration of the application in which it is created. It maintains its state between client invocations but its state is not required to survive container shutdown or crash.
A singleton session bean is intended to be shared, and it supports concurrent access.
A singleton session bean must not implement
the jakarta.ejb.SessionSynchronization
interface or use the session
synchronization annotations.
The following steps describe the life cycle of a singleton session bean instance:
-
A singleton session bean instance’s life starts when the container invokes the session bean class constructor to create the singleton bean instance.[30] Next, the container performs any dependency injection as specified by the metadata annotations on the bean class or by the deployment descriptor. The container then calls the
PostConstruct
lifecycle callback interceptor methods for the bean, if any. -
The singleton bean instance is now ready to be delegated a business method call from any client or a call from the container to a timeout callback method.
-
When the application is shutting down, the container invokes the
PreDestroy
lifecycle callback interceptor methods on the singleton session bean instance, if any. This ends the life of the singleton session bean instance.
4.8.1. Singleton Session Bean Initialization
By default, the container is responsible for
deciding when to initialize a singleton session bean instance. However,
the Bean Provider can optionally configure the singleton session bean
for eager initialization. If the Startup
annotation appears on the
singleton session bean class or if the singleton session bean has been
designated via the deployment descriptor as requiring eager
initialization, the container must initialize the singleton session bean
instance during the application startup sequence. The container must
initialize all such startup-time singleton session beans before any
external client requests (that is, client requests originating outside
of the application) are delivered to any enterprise bean components in
the application.
The following example shows a singleton session bean with startup logic that initializes its shared state:
@Startup
@Singleton
public class SharedBean implements Shared {
private SharedData state;
@PostConstruct
void init() {
// initialize shared data
...
}
...
}
In some cases, explicit initialization
ordering dependencies exist between multiple singleton session bean
components in an application. The DependsOn
annotation is used to
express these dependencies. A DependsOn
dependency is used in cases
where one singleton session bean must initialize before one or more
other singleton session beans. The container ensures that all singleton
session beans with which a singleton session bean has a DependsOn
relationship have been initialized before the PostConstruct
method is
called.
Note that if one singleton session bean
merely needs to invoke another singleton session bean from its
PostConstruct
method, no explicit ordering metadata is required. In that
case, the first singleton session bean would merely use an Enterprise Beans reference
to invoke the target singleton session bean. In this case, the
acquisition of the Enterprise Beans reference (either through injection or lookup)
does not necessarily imply the actual creation of the corresponding
singleton session bean instance.
The following examples illustrate the use of
DependsOn
metadata:
@Singleton
public class B { ... }
@DependsOn("B")
@Singleton
public class A { ... }
In the above example, the container must
guarantee that singleton B
is initialized before singleton A
. The
DependsOn
value attribute holds one or more strings, where each
specifies the ejb-name
of the target singleton session bean.
In the following example, the container must
guarantee that singletons B
and C
are initialized before singleton
A
. In the case of multiple values, the ordering in which the target
ejb-name
values are listed is not preserved at runtime. For example, if
singleton B
has an ordering dependency on singleton C
, it is
singleton B
’s responsibility to explicitly capture that in its own
metadata.
@Singleton
public class B { ... }
@Singleton(name="Cbean")
public class C { ... }
@DependsOn({"B", "Cbean"})
@Singleton
public class A { ... }
The following example illustrates the use of
the fully-qualified ejb-name
syntax to refer to a singleton session bean
packaged within a different module in the same application.
// two Singleton components packaged in different ejb-jars within
// the same .ear
// packaged in b.jar
@Singleton
public class B { ... }
// packaged in a.jar
@DependsOn("b.jar#B")
@Singleton
public class A { ... }
Circular dependencies within the DependsOn
metadata are not permitted. Circular dependencies are not required to be
detected by the container but may result in a deployment error.
4.8.2. Singleton Session Bean Destruction
Any singleton session bean instance that
successfully completes initialization is removed by the container during
application shutdown. At this time the container must invoke the
PreDestroy
lifecycle callback interceptor methods on the singleton
session bean instance, if any. The container ensures that all singleton
session beans with which a singleton session bean has a DependsOn
relationship are still available during the PreDestroy
callback. After
the PreDestroy
callback completes, the container ends the life of the
singleton session bean instance.
4.8.3. Transaction Semantics of Initialization and Destruction
The PostConstruct
and PreDestroy
methods
of singleton session beans with container-managed transaction
demarcation can be invoked with or without a transaction. From the Bean
Provider’s view there is no client of a PostConstruct
or PreDestroy
method.
A PostConstruct
or PreDestroy
method of a
singleton session bean with container-managed transaction demarcation is
permitted to have transaction attribute REQUIRED
, REQUIRES_NEW
, or
NOT_SUPPORTED
(Required
, RequiresNew
, or NotSupported
if the
deployment descriptor is used to specify the transaction attribute).
Note that the container must start a new
transaction if the REQUIRED
(Required
) transaction attribute
is used. This guarantees, for example, that the transactional behavior
of the PostConstruct
method is the same regardless of whether the
singleton session bean instance is initialized eagerly at container
startup time or as a side effect of a first client invocation on the
singleton session bean. The REQUIRED
transaction attribute value is
allowed so that specification of a transaction attribute for the
singleton session bean’s PostConstruct
and PreDestroy
methods
can be defaulted.
4.8.4. Singleton Session Bean Error Handling
Errors occurring during singleton session
bean initialization are considered fatal and must result in the
discarding of the singleton session bean instance. Possible
initialization errors include injection failure, a system exception
thrown from an AroundConstruct
or PostConstruct
method, or the failure
of a PostConstruct
method’s container-managed transaction to
successfully commit. If a singleton session bean fails to initialize,
attempted invocations on the singleton session bean result in the
jakarta.ejb.NoSuchEJBException
exception as defined by Session Bean’s Business Interface
and Session Bean’s No-Interface View.
The same singleton session bean instance must remain active until application shutdown. Unlike instances of other component types, system exceptions thrown from business methods or callbacks of a singleton session bean do not result in the destruction of the singleton instance.
4.8.5. Singleton Session Bean Concurrency
From the client’s perspective, a singleton session bean always supports concurrent access. In general, the client of a singleton session bean does not have to concern itself with whether other clients might be accessing the singleton session bean at the same time.
From the Bean Provider’s perspective, there are two approaches for controlling singleton session bean concurrency behavior:
-
container-managed concurrency: the container controls concurrent access to the bean instance based on method-level locking metadata
-
bean-managed concurrency: the container allows full concurrent bean instance access and defers state synchronization responsibility to the Bean Provider
When designing a singleton session bean, the bean provider must decide whether the bean will use container-managed or bean-managed concurrency. Typically singleton session beans will be specified to have container-managed concurrency. This is the default if no concurrency management type is specified. A singleton session bean can be designed to use either container-managed concurrency or bean-managed concurrency but it cannot use both.
The lifecycle of any interceptor classes associated with a singleton session bean have the same lifecycle and concurrency behavior as that of the singleton session bean itself. Each interceptor class will be instantiated once per singleton session bean instance. Any state stored in an instance of an interceptor class associated with a singleton session bean should be considered when devising the concurrency plan for the bean.
It is legal to store Jakarta EE objects that do not support concurrent access (e.g. references to Jakarta Persistence entity managers or stateful session beans) within the singleton session bean instance state. However, it is the responsibility of the Bean Provider to ensure such objects are not accessed by more than one thread at a time.
Independent of the bean’s concurrency
management type, the container must ensure that no concurrent access to
the singleton session bean instance occurs until after the instance has
successfully completed its initialization sequence, including any
PostConstruct
lifecycle callback method(s). The container must
temporarily block any singleton session bean access attempts that arrive
while the singleton session bean is still initializing.
Independent of the bean’s concurrency
management type, the container must ensure that concurrent access to the
SessionContext
object is thread-safe.
Singleton session beans support reentrant calls, i.e., where an outbound call from a singleton session bean method results in a loopback call to the singleton session bean on the same thread. Reentrant singleton session beans should be programmed and used with caution. Special locking semantics apply to loopback calls on singleton session beans with container-managed concurrency as described below.
4.8.5.1. Container-Managed Concurrency
With container-managed concurrency, the container is responsible for controlling concurrent access to the bean instance based on method-level locking metadata. Each business method or timeout method is associated with either a read (shared) lock or a write (exclusive) lock.
If the container invokes a method associated with a read lock, any number of other concurrent invocations on methods with read locks are allowed to access the bean instance simultaneously.
If the container invokes a method associated with a write lock, no other concurrent invocations will be allowed to proceed until the method holding the write lock completes its processing.
A concurrent access attempt that is not
allowed to proceed due to locking is blocked until it can make forward
progress. Timeouts can be specified via metadata so that a blocked
request can be rejected if a lock is not acquired within a certain
amount of time. If a singleton session bean invocation is rejected due
to lock timeout the ConcurrentAccessTimeoutException
is thrown to the
client.
This specification only mandates the basic read and write locking semantics outlined above. There are many policy decisions that a container could make to affect the performance of the locking scheme for a given application. For example:
-
Determining whether to grant forward progress to a read method or write method, when both readers and writers are waiting at the time that a write method completes.
-
Determining whether to allow additional readers while one or more readers is active and a writer is waiting.
The exact set of additional read/write locking policy decisions supported by a Container Provider and the configuration requirements for those policies are outside the scope of this specification.
Reentrant Locking Behavior
Special locking semantics apply to loopback calls on singleton session beans with container-managed concurrency.
If a loopback call occurs on a singleton session bean that already holds a write lock on the same thread:
-
If the target of the loopback call is a read method, the read lock must always be granted immediately, without releasing the original write lock.
-
If the target of the loopback call is a write method, the call must proceed immediately, without releasing the original write lock.
If a loopback call occurs on a singleton session bean that holds a read lock on the same thread (but does not also hold a write lock on the same thread):
-
If the target of the loopback call is a read method, the call must proceed immediately, without releasing the original
Read
lock. -
If the target of the loopback call is a write method, the
jakarta.ejb.IllegalLoopbackException
must be thrown to the caller.
4.8.5.2. Bean-Managed Concurrency
With bean-managed concurrency, the container
allows full concurrent access to the singleton session bean instance. It
is the responsibility of the Bean Provider to guard its state as
necessary against synchronization errors due to concurrent access. The
Bean Provider is permitted to use the Java language level
synchronization primitives such as synchronized
and volatile
for this
purpose.
4.8.5.3. Specification of a Concurrency Management Type
By default, a singleton session bean has
container-managed concurrency. The Bean Provider of a singleton session
bean can use the ConcurrencyManagement
annotation on the bean class to
declare the bean’s concurrency management type.
Alternatively, the Bean Provider can use the deployment descriptor to specify the bean’s concurrency management type. If the deployment descriptor is used, it is only necessary to explicitly specify the bean’s concurrency management type if bean-managed concurrency is used.
The concurrency management type of a singleton session bean is determined by the Bean Provider. The Application Assembler is not permitted to use the deployment descriptor to override a bean’s concurrency management type regardless of whether it has been explicitly specified or defaulted by the Bean Provider. (See Deployment Descriptor for information about the deployment descriptor.)
4.8.5.4. Specification of the Container-Managed Concurrency Metadata for a Bean’s Methods
The Bean Provider of a singleton session bean with container-managed concurrency may specify locking metadata for the enterprise bean’s methods. By default, the value of the lock associated with a method of a bean with container managed concurrency is a write lock (exclusive lock).
A concurrency locking attribute is a value associated with each of the following methods:
-
a method of a bean’s business interface
-
a method of a bean’s no-interface view
-
a timeout callback method
-
a web service endpoint method
The concurrency locking attribute specifies how the container must manage concurrency when a client invokes the method.
Concurrency locking attributes are specified for the following methods:
-
For a bean written to the Enterprise Beans 3.x client view API, the concurrency locking attributes are specified for those methods of the bean class that correspond to the bean’s business interface, the direct and indirect superinterfaces of the business interface, methods exposed through the no-interface view, and for timeout callback methods, if any.
-
For a bean that provides a web service client view, the concurrency locking attributes are specified for those methods of the bean class that correspond to the bean’s web service endpoint methods, and for timeout callback methods, if any.
The following rules apply to the specification of concurrency attributes.
The Lock(READ)
and Lock(WRITE)
annotations are
used to specify concurrency locking attributes.
The concurrency locking attributes for the methods of a bean class may be specified on the class, the business methods of the class, or both.
Specifying the Lock
annotation on the bean
class means that it applies to all applicable business methods of the
class. If the concurrency locking attribute is not specified, it is
assumed to be Lock(WRITE)
. The absence of a concurrency attribute
specification on the bean class is equivalent to the specification of
Lock(WRITE)
on the bean class.
A concurrency locking attribute may be specified on a method of the bean class to override the concurrency locking attribute value explicitly or implicitly specified on the bean class.
If the bean class has superclasses, the following additional rules apply:
-
A concurrency locking attribute specified on a superclass S appplies to the business methods defined by S. If a class-level concurrency attribute is not specified on S, it is equivalent to specification of
Lock(WRITE)
on S. -
A concurrency locking attribute may be specified on a business method M defined by class S to override for method M the concurrency locking attribute value explicitly or implicitly specified on the class S.
-
If a method M of class S overrides a business method defined by a superclass of S, the concurrency locking attribute of M is determined by the above rules as applied to class S.
The Bean Provider may use the deployment
descriptor as an alternative to metadata annotations to specify the
concurrency locking attributes. Concurrency locking attributes specified
in the deployment descriptor are assumed to override or supplement
concurrency locking attributes specified in annotations. If a
concurrency locking attribute value is not specified in the deployment
descriptor, it is assumed that the concurrency locking attribute
specified in annotations applies, or — in the case that no annotation
has been specified —that the value is Write
.
The Application Assembler is permitted to override the concurrency locking attribute values using the bean’s deployment descriptor. The Deployer is also permitted to override the concurrency locking attribute values at deployment time. Caution should be exercised when overriding the concurrency locking attributes of an application, as the concurrency structure of an application is typically intrinsic to the semantics of the application.
Example:
@Lock(READ)
public class SomeClass {
public void aMethod () { ... }
public void bMethod () { ... }
...
}
@Singleton
public class ABean extends SomeClass implements A {
public void aMethod () { ... }
@Lock(WRITE)
public void cMethod () { ... }
...
}
Assuming that aMethod
, bMethod
, cMethod
of
singleton session bean ABean
are methods of business interface A
, their
concurrency locking attributes are Lock(WRITE)
, Lock(READ)
, and
Lock(WRITE)
respectively.
4.8.5.5. Concurrent Access Timeouts
A concurrent access attempt that cannot
immediately acquire the appropriate lock is blocked until it can make
forward progress. The AccessTimeout
annotation is used to specify the
amount of time the access attempt should be blocked before timing out.
Access timeouts only apply to methods eligible for concurrency locks on
a singleton session bean with container-managed concurrency. If an
access attempt times out, the container throws the
jakarta.ejb.ConcurrentAccessTimeoutException
to the client.
The AccessTimeout
annotation can be specified
on a business method or on a bean class (or superclass). An
AccessTimeout
annotation specified on a class applies the access timeout
to all business methods of that class. If the AccessTimeout
annotation
is specified on both a class and on a business method of that class, the
method-level annotation takes precedence.
An AccessTimeout
value of -1
indicates that
the client request will block indefinitely until forward progress can be
made.
An AccessTimeout
value of 0
indicates that
concurrent access is not allowed. Access attempts on methods with a
timeout value of 0
result in the jakarta.ejb.ConcurrentAccessException
.
4.8.6. Operations Allowed in the Methods of a Singleton Session Bean
Operations Allowed in the Methods of a Singleton Session Bean defines
the methods of a singleton session bean class in which the session bean
instances can access the methods of the jakarta.ejb.SessionContext
interface, the java:comp/env
environment naming context, resource
managers, TimerService
and Timer
methods, the EntityManager
and
EntityManagerFactory
methods, and other enterprise beans.
If a session bean instance attempts to invoke
a method of the SessionContext
interface, and the access is not allowed
in Operations Allowed in the Methods of a Singleton Session Bean, the container must throw the
java.lang.IllegalStateException
.
If a session bean instance attempts to invoke
a method of the TimerService
or Timer
interface and the access is
not allowed in Operations Allowed in the Methods of a Singleton Session Bean, the container must throw
the java.lang.IllegalStateException
.
If a session bean instance attempts to access a resource manager, an enterprise bean, an entity manager or entity manager factory, and the access is not allowed in Operations Allowed in the Methods of a Singleton Session Bean, the behavior is undefined by the Enterprise Beans architecture.
Bean method | Bean method can perform the following operations | |
---|---|---|
Container-managed transaction demarcation |
Bean-managed transaction demarcation |
|
constructor |
- |
- |
dependency injection methods |
JNDI access to java:comp/env |
JNDI access to java:comp/env |
PostConstruct, PreDestroy lifecycle callback interceptor methods Note A |
JNDI access to java:comp/env |
UserTransaction methods |
business method from business interface or from no-interface view; business method interceptor method |
JNDI access to java:comp/env |
UserTransaction methods |
business method from web service endpoint |
Message context methods |
UserTransaction methods |
timeout callback method |
JNDI access to java:comp/env |
UserTransaction methods |
Notes:
[A] If a client calls lifecycle
callback method through a business interface or a no-interface view,
the method is treated like a business method.
Additional restrictions:
-
The
getRollbackOnly
andsetRollbackOnly
methods of theSessionContext
interface should be used only in the session bean methods that execute in the context of a transaction. The container must throw thejava.lang.IllegalStateException
if the methods are invoked while the current business method is not executing in the context of a transaction. -
Invoking the
wasCancelCalled
method is disallowed except when inside the context of the asynchronous methods that declareFuture<V>
object as the returning type
The reasons for disallowing operations in Operations Allowed in the Methods of a Singleton Session Bean:
-
Invoking the
getBusinessObject
method is disallowed if the session bean does not define a business interface or a no-interface view. -
Invoking the
getInvokedBusinessInterface
method is disallowed if the session bean does not define a business interface or a no-interface view. It is also disallowed if the current business method was not invoked through a business interface or the no-interface view. -
Invoking the
getEJBObject
andgetEJBHome
methods is disallowed since a singleton session bean does not support the Enterprise Beans 2.x remote client view. -
Invoking the
getEJBLocalObject
andgetEJBLocalHome
methods is disallowed since a singleton session bean does not support the Enterprise Beans 2.x local client view. -
Invoking the
getRollbackOnly
andsetRollbackOnly
methods is disallowed in the session bean methods for which the container does not have a meaningful transaction context, and for all session beans with bean-managed transaction demarcation. -
Accessing resource managers, enterprise beans, and the
EntityManager
is disallowed in the session bean methods for which the container does not have a meaningful transaction context and/or client security context. -
The
UserTransaction
interface is unavailable to session beans with container-managed transaction demarcation.
4.9. The Responsibilities of the Bean Provider
This section describes the responsibilities of the session Bean Provider to ensure that a session bean can be deployed in any Enterprise Beans container. These requirements apply to stateful session beans, stateless session beans, and singleton session beans.
4.9.1. Classes and Interfaces
The session Bean Provider is responsible for providing the following class files:[31]
-
Session bean class.
-
Session bean’s business interface(s), if the session bean provides an Enterprise Beans 3.x local or remote client view.
-
Session bean’s remote interface and remote home interface, if the session bean provides an Enterprise Beans 2.1 remote client view.
-
Session bean’s local interface and local home interface, if the session bean provides an Enterprise Beans 2.1 local client view.
-
Session bean’s web service endpoint interface, if any.
-
Interceptor classes, if any.
4.9.2. Session Bean Class
The following are the requirements for the session bean class:
-
The class must be defined as
public
, must not befinal
, and must not beabstract
. The class must be a top level class. -
The class must have a
public
constructor that takes no parameters. The Enterprise Beans container uses this constructor to create instances of the session bean class. -
The class must not define the
finalize()
method. -
The class must implement the bean’s business interface(s) or the methods of the bean’s business interface(s), if any.
-
The class must implement the business methods of the bean’s Enterprise Beans 2.1 client view interfaces, if any. [32]
Optionally:
-
The class may have an additional constructor annotated with the
Inject
annotation (see Relationship to Jakarta Contexts and Dependency Injection and the CDI specification [8]). -
The class may implement, directly or indirectly, the
jakarta.ejb.SessionBean
interface.[33] -
If the class is a stateful session bean, it may implement the
jakarta.ejb.SessionSynchronization
interface or use one or more of the session synchronization annotations. -
The class may implement the session bean’s web service endpoint or component interface.
-
If the class is a stateless session bean, it may implement the
jakarta.ejb.TimedObject
interface. See Timer Service. -
The class may implement the
ejbCreate
method(s). -
The session bean class may have superclasses and/or superinterfaces. If the session bean has superclasses, the business methods, lifecycle callback interceptor methods, the timeout callback methods, the methods implementing the optional session synchronization notifications, the
Init
orejbCreate<METHOD>
methods, theRemove
methods, and the methods of theSessionBean
interface may be defined in the session bean class or in any of its superclasses. -
The session bean class is allowed to implement other methods (for example helper methods invoked internally by the business methods) in addition to the methods required by the Enterprise Beans specification.
4.9.2.1. Session Bean Superclasses
A session bean class is permitted to have superclasses that are themselves session bean classes. However, there are no special rules that apply to the processing of annotations or the deployment descriptor for this case. For the purposes of processing a particular session bean class, all superclass processing is identical regardless of whether the superclasses are themselves session bean classes. In this regard, the use of session bean classes as superclasses merely represents a convenient use of implementation inheritance, but does not have component inheritance semantics.
For example, the client views exposed by a particular session bean are not inherited by a subclass that also happens to define a session bean.
@Stateless
public class A implements Foo { ... }
@Stateless
public class B extends A implements Bar { ... }
Assuming Foo
and Bar
are local business
interfaces and there is no associated deployment descriptor, session
bean A
exposes local business interface Foo
and session bean B
exposes
local business interface Bar
, but not Foo
.
Session bean B
would need to explicitly
include Foo
in its set of exposed views for that interface to apply. For
example:
@Stateless
public class A implements Foo { ... }
@Stateless
public class B extends A implements Foo, Bar { ... }
4.9.3. Lifecycle Callback Interceptor Methods
The AroundConstruct
, PostConstruct
,
PreDestroy
, PrePassivate
, and PostActivate
lifecycle callback
interceptor methods may be defined for session beans. If the
PrePassivate
or PostActivate
lifecycle callbacks are defined for
stateless session beans or singleton session beans, they are
ignored.[34]
The AroundConstruct
lifecycle callback
interceptor method may be defined on an interceptor class only. All
other lifecycle callback interceptor methods may be defined on the bean
class and/or on an interceptor class of the bean. Rules applying to the
definition of lifecycle callback interceptor methods are defined in
Interceptors for LifeCycle Event Callbacks.
Compatibility Note: If the PostConstruct
lifecycle callback
interceptor method is the ejbCreate
method, if the PreDestroy
lifecycle callback interceptor method is the ejbRemove
method, if the
PostActivate
lifecycle callback interceptor method is the
ejbActivate
method, or if the PrePassivate
lifecycle callback
interceptor method is the ejbPassivate
method, these callback methods
must be implemented on the bean class itself (or on its superclasses).
Except for these cases, the method names can be arbitrary, but must not
start with "ejb" to avoid conflicts with the callback methods defined by
the jakarta.ejb.EnterpriseBean
interfaces.
4.9.4. Session Synchronization Methods
The bean class (or superclass) of a stateful
session bean may use one or more of the session synchronization
annotations AfterBegin
, BeforeCompletion
, and AfterCompletion
. Each bean
has at most one session synchronization method for each of the three
annotation types. In the case of method overriding of session
synchronization methods declared by annotations, the most derived method
takes precedence. The signatures of the session synchronization methods
must follow these rules:
-
The method must not be declared as final or static.
-
The method may have any access type: public, private, protected, or package-level.
-
The return type must be void.
-
The
AfterBegin
andBeforeCompletion
methods must take0
arguments. -
The
AfterCompletion
method must take a single argument of typeboolean
.
4.9.5. ejbCreate<METHOD> Methods
The session bean
class of a session bean that has a home interface may define one or more
ejbCreate<METHOD>
methods. These ejbCreate
methods are intended for
use only with components written to the the Enterprise Beans 2.1 and earlier APIs.
The signatures of the ejbCreate
methods must follow these rules:
-
The method name must have ejbCreate as its prefix.
-
The method must be declared as public.
-
The method must not be declared as final or static.
-
The return type must be void.
-
The method arguments must be legal types for RMI/IIOP if there is a
create<METHOD>
corresponding to theejbCreate<METHOD>
method on the session bean’s remote home interface. -
A stateless session bean may define only a single
ejbCreate
method, with no arguments. -
The
throws
clause may define arbitrary application exceptions, possibly including thejakarta.ejb.CreateException
.
Compatibility Note: Enterprise Beans 1.0 allowed the ejbCreate
method to
throw the java.rmi.RemoteException
to indicate a non-application
exception. This practice was deprecated in Enterprise Beans 1.1—
an Enterprise Beans 1.1 or Enterprise Beans 2.0
or later compliant enterprise bean should throw the
jakarta.ejb.EJBException
or another RuntimeException
to indicate
non-application exceptions to the container (see System Exceptions). An Enterprise Beans 2.0 and
later compliant enterprise bean should not throw the
java.rmi.RemoteException
from the ejbCreate
method.
4.9.6. Business Methods
The session bean class may define zero or more business methods whose signatures must follow these rules:
-
The method names can be arbitrary, but they must not start with "ejb" to avoid conflicts with the callback methods used by the Enterprise Beans architecture.
-
The method must be declared as public.
-
The method must not be declared as final or static.
-
The argument and return value types for the method must be legal types for RMI/IIOP if the method corresponds to a business method on the session bean’s remote business interface or remote component interface.
-
The argument and return value types for a method must be legal types for Jakarta XML Web Services if the method is a web service method or corresponds to a method on the session bean’s web service endpoint.
-
The
throws
clause may define arbitrary application exceptions.
Compatibility Note: Enterprise Beans 1.0 allowed the business methods to throw
the java.rmi.RemoteException
to indicate a non-application exception.
This practice was deprecated in Enterprise Beans 1.1—
an Enterprise Beans 1.1 or Enterprise Beans 2.0 or later
compliant enterprise bean should throw the jakarta.ejb.EJBException
or
another RuntimeException
to indicate non-application exceptions to the
container (see System Exceptions). An Enterprise Beans 2.0 or later compliant enterprise bean
should not throw the java.rmi.RemoteException
from a business method.
4.9.7. Session Bean’s Business Interface
The following are the requirements for the session bean’s business interface:
-
The interface must not extend the
jakarta.ejb.EJBObject
orjakarta.ejb.EJBLocalObject
interface.
If the business interface is a remote
business interface, the argument and return values must be of valid
types for RMI/IIOP. The remote business interface is not required or
expected to be a java.rmi.Remote
interface. The throws
clause should
not include the java.rmi.RemoteException
. The methods of the business
interface may only throw the java.rmi.RemoteException
if the interface
extends java.rmi.Remote
.
-
The interface is allowed to have superinterfaces.
-
If the interface is a remote business interface, its methods must not expose local interface types, timers or timer handles as arguments or results.
-
The same business interface cannot be both a local and a remote business interface of the bean.[35]
-
The bean class must implement the interface or the interface must be designated as a local or remote business interface of the bean by means of the
Local
orRemote
annotation or in the deployment descriptor. The following rules apply to the interfaces implemented by the bean class:-
java.io.Serializable
,java.io.Externalizable
and the interfaces defined by thejakarta.ejb
package are excluded when determining whether the bean class has business interfaces. -
All business interfaces must be explicitly designated as such if any of the following is true:
-
the bean exposes a no-interface view
-
any interface of the bean class is explicitly designated as a business interface of the bean by either of the following means:
-
using the
Local
orRemote
annotation with a non-empty value on the bean class -
using the
Local
orRemote
annotation on the interface -
in the deployment descriptor
-
-
Otherwise:
-
If the bean class is annotated with the
Remote
annotation, all implemented interfaces (excluding the interfaces listed above) are assumed to be remote business interfaces of the bean. -
If the bean class is annotated with the
Local
annotation, or if the bean class is annotated with neither theLocal
nor theRemote
annotation, all implemented interfaces (excluding the interfaces listed above) are assumed to be local business interfaces of the bean.
-
-
-
Note that while it is expected that the bean class will typically implement its business interface(s), if the bean class uses annotations or the deployment descriptor to designate its business interface(s), it is not required that the bean class also be specified as implementing the interface(s).
The following examples assume that there is no deployment descriptor associated with the bean and neither the Local nor the Remote annotation is specified on the bean class or an interface unless noted.
Example 1: session bean A exposes two local
business interfaces, Foo
and Bar
:
public interface Foo { ... }
public interface Bar { ... }
@Stateless
public class A implements Foo, Bar { ... }
Example 2: session bean A exposes two local
business interfaces, Foo
and Bar
:
public interface Foo { ... }
public interface Bar { ... }
@Local
@Stateless
public class A implements Foo, Bar { ... }
Example 3: session bean A exposes two remote
business interfaces, Foo
and Bar
public interface Foo { ... }
public interface Bar { ... }
@Remote
@Stateless
public class A implements Foo, Bar { ... }
Example 4: session bean A exposes only one
remote business interface Foo
@Remote
public interface Foo { ... }
public interface Bar { ... }
@Stateless
public class A implements Foo, Bar { ... }
Example 5: session bean A exposes only one
remote business interface Foo
public interface Foo { ... }
public interface Bar { ... }
@Remote(Foo.class)
@Stateless
public class A implements Foo, Bar { ... }
4.9.8. Session Bean’s No-Interface View
The following are the requirements for a session bean that exposes a no-interface view:
-
The bean class must designate that it exposes a no-interface view via its bean class definition or in the deployment descriptor. The following rules apply:
-
If the bean does not expose any other client views (local, remote, no-interface, 2.x Remote Home, 2.x Local Home, Web Service) and its implements clause is empty, the bean defines a no-interface view.
-
If the bean exposes at least one other client view, the bean designates that it exposes a no-interface view by means of the LocalBean annotation on the bean class or in the deployment descriptor.
-
The following interfaces are excluded when determining whether the bean exposes a no-interface view:
java.io.Serializable
;java.io.Externalizable
; any of the interfaces defined by thejakarta.ejb
package. -
All non-static public methods of the bean class and of any superclasses except java.lang.Object are exposed as business methods through the no-interface view.
-
-
The
throws
clause of a bean class method exposed through the no-interface view must not include the java.rmi.RemoteException. -
Only
private
methods of the bean class and any superclasses exceptjava.lang.Object
may be declaredfinal
.
4.9.9. Session Bean’s Remote Component Interface
The following are the requirements for the session bean’s remote component interface:
-
The interface must extend the
jakarta.ejb.EJBObject
interface. -
The methods defined in this interface must follow the rules for RMI/IIOP. This means that their argument and return values must be of valid types for RMI/IIOP, and their
throws
clauses must include thejava.rmi.RemoteException
. -
The remote component interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI/IIOP rules for the definition of remote interfaces.
-
For each method defined in the remote component interface, there must be a matching method in the session bean’s class. The matching method must have:
-
The same name.
-
The same number and types of arguments, and the same return type.
-
All the exceptions defined in the
throws
clause of the matching method of the session bean class must be defined in thethrows
clause of the method of the remote component interface.
-
-
The remote component interface methods must not expose local component interface types, local home interface types, timers or timer handles as arguments or results.
4.9.10. Session Bean’s Remote Home Interface
The following are the requirements for the session bean’s remote home interface:
-
The interface must extend the
jakarta.ejb.EJBHome
interface. -
The methods defined in this interface must follow the rules for RMI/IIOP. This means that their argument and return values must be of valid types for RMI/IIOP, and that their
throws
clauses must include thejava.rmi.RemoteException
. -
The remote home interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI/IIOP rules for the definition of remote interfaces.
-
A session bean’s remote home interface must define one or more
create<METHOD>
methods. A stateless session bean must define exactly one create method with no arguments. -
Each create method of a stateful session bean must be named
create<METHOD>
, and it must match one of theInit
methods orejbCreate<METHOD>
methods defined in the session bean class. The matchingInit
method orejbCreate<METHOD>
method must have the same number and types of arguments. (Note that the return type is different.) Thecreate
method for a stateless session bean must be named"create"
but need not have a matching"ejbCreate"
method. -
The return type for a
create<METHOD>
method must be the session bean’s remote component interface type. -
All the exceptions defined in the
throws
clause of anejbCreate<METHOD>
method of the session bean class must be defined in thethrows
clause of the matchingcreate<METHOD>
method of the remote home interface. -
The
throws
clause must includejakarta.ejb.CreateException
.
4.9.11. Session Bean’s Local Component Interface
The following are the requirements for the session bean’s local component interface:
-
The interface must extend the
jakarta.ejb.EJBLocalObject
interface. -
The
throws
clause of a method defined in the local interface must not include thejava.rmi.RemoteException
. -
The local component interface is allowed to have superinterfaces.
-
For each method defined in the local component interface, there must be a matching method in the session bean’s class. The matching method must have:
-
The same name.
-
The same number and types of arguments, and the same return type.
-
All the exceptions defined in the
throws
clause of the matching method of the session bean class must be defined in thethrows
clause of the method of the local component interface.
-
4.9.12. Session Bean’s Local Home Interface
The following are the requirements for the session bean’s local home interface:
-
The interface must extend the jakarta.ejb.EJBLocalHome interface.
-
The
throws
clause of a method in the local home interface must not include thejava.rmi.RemoteException
. -
The local home interface is allowed to have superinterfaces.
-
A session bean’s local home interface must define one or more
create<METHOD>
methods. A stateless session bean must define exactly one create method with no arguments. -
Each create method of a stateful session bean must be named
create<METHOD>
, and it must match one of theInit
methods orejbCreate<METHOD>
methods defined in the session bean class. The matchingInit
method orejbCreate<METHOD>
method must have the same number and types of arguments. (Note that the return type is different.) Thecreate
method for a stateless session bean must be named"create"
but need not have a matching"ejbCreate"
method. -
The return type for a
create<METHOD>
method must be the session bean’s local component interface type. -
All the exceptions defined in the
throws
clause of anejbCreate<METHOD>
method of the session bean class must be defined in thethrows
clause of the matchingcreate<METHOD>
method of the local home interface. -
The
throws
clause must includejakarta.ejb.CreateException
.
4.10. The Responsibilities of the Container Provider
This section describes the responsibilities of the Container Provider to support a session bean. The Container Provider is responsible for providing the deployment tools and for managing the session bean instances at runtime.
Because the Enterprise Beans specification does not define the API between deployment tools and the container, we assume that the deployment tools are provided by the Container Provider. Alternatively, the deployment tools may be provided by a different vendor who uses the container vendor’s specific API.
4.10.1. Generation of Implementation Classes
The deployment tools provided by the container are responsible for the generation of additional classes when the session bean is deployed. The tools obtain the information that they need for generation of the additional classes by introspecting the classes and interfaces provided by the Bean Provider and by examining the session bean’s deployment descriptor.
The deployment tools must generate the following classes:
-
A class that implements the session bean’s business interface.
-
A class that implements the session bean’s no-interface view.
-
A class that implements the session bean’s remote home interface (session EJBHome class).
-
A class that implements the session bean’s remote component interface (session EJBObject class).
-
A class that implements the session bean’s local home interface (session EJBLocalHome class).
-
A class that implements the session bean’s local component interface (session EJBLocalObject class).
-
A class that implements the session bean’s web service endpoint.
-
A class that implements the return value of an asynchronous method with return type
Future<V>
.
The deployment tools may also generate a class that mixes some container-specific code with the session bean class. This code may, for example, help the container to manage the bean instances at runtime. The tools can use subclassing, delegation, and code generation.
The deployment tools may also allow the
generation of additional code that wraps the business methods and is
used to customize the business logic to an existing operational
environment. For example, a wrapper for a debit
function on the
AccountManager
bean may check that the debited amount does not exceed a
certain limit.
4.10.3. Session Business Interface Implementation Class
The container’s implementation of the session business interface, which is generated by the deployment tools, implements the business methods specific to the session bean.
The implementation of each business method must activate the instance (if the instance is in the passive state), invoke any business method interceptor methods, and invoke the matching business method on the instance.
The Container Provider is responsible for
providing the implementation of the equals
and hashCode
methods for
the business interface, in conformance with the requirements of Session Object Identity.
4.10.4. No-Interface View Reference Class
The container’s implementation of the no-interface view reference, which is generated by the deployment tools, implements the business methods that are exposed to the no-interface view client.
The implementation of each business method must activate the instance (if the instance is in the passive state), invoke any business method interceptor methods, and invoke the matching business method on the instance.
The Container Provider is responsible for
providing the implementation of the equals
and hashCode
methods for
the no-interface view reference class, in conformance with the
requirements of Client view of Session Object’s Life Cycle.
4.10.5. Session EJBHome Class
The session
EJBHome class, which is generated by the deployment tools, implements
the session bean’s remote home interface. This class implements the
methods of the jakarta.ejb.EJBHome
interface and the create<METHOD>
methods specific to the session bean.
The implementation of each create<METHOD>
method invokes a matching ejbCreate<METHOD>
method.
4.10.6. Session EJBObject Class
The session
EJBObject class, which is generated by the deployment tools, implements
the session bean’s remote component interface. It implements the methods
of the jakarta.ejb.EJBObject
interface and the business methods specific
to the session bean.
The implementation of each business method must activate the instance (if the instance is in the passive state), invoke any business method interceptor methods, and invoke the matching business method on the instance.
4.10.7. Session EJBLocalHome Class
The session
EJBLocalHome class, which is generated by the deployment tools,
implements the session bean’s local home interface. This class
implements the methods of the jakarta.ejb.EJBLocalHome
interface and the
create<METHOD>
methods specific to the session bean.
The implementation of each create<METHOD>
method invokes a matching ejbCreate<METHOD>
method.
4.10.8. Session EJBLocalObject Class
The session
EJBLocalObject class, which is generated by the deployment tools,
implements the session bean’s local component interface. It implements
the methods of the jakarta.ejb.EJBLocalObject
interface and the business
methods specific to the session bean.
The implementation of each business method must activate the instance (if the instance is in the passive state), invoke any business method interceptor methods, and invoke the matching business method on the instance.
4.10.9. Web Service Endpoint Implementation Class
The implementation class for a stateless session bean’s web service endpoint is generated by the container’s deployment tools. This class must handle requests to the web service endpoint, unmarshall the SOAP request, invoke any business method interceptor methods, and invoke the stateless session bean method that matches the web service endpoint method that corresponds to the request.
4.10.10. Asynchronous Client Future<V> Return Value Implementation Class
The object returned from an asynchronous
method with return type Future<V>
is implemented by the container’s
deployment tools.
4.10.11. Handle Classes
The deployment tools are responsible for implementing the handle classes for the session bean’s remote home and remote component interfaces.
4.10.12. EJBMetaData Class
The deployment tools are responsible for
implementing the class that provides metadata to the remote client view
contract. The class must be a valid RMI Value class and must implement
the jakarta.ejb.EJBMetaData
interface.
4.10.13. Non-reentrant Instances
The container must ensure that only one thread can be executing a stateless or stateful session bean instance at any time. Therefore, stateful and stateless session beans do not have to be coded as reentrant. One implication of this rule is that an application cannot make loopback calls to a stateless or stateful session bean instance.
4.10.14. Transaction Scoping, Security, Exceptions
The container must follow the rules with respect to transaction scoping, security checking, and exception handling, as described in Support for Transactions, Security Management, and Exception Handling, respectively.
4.10.15. Jakarta XML Web Services Message Handlers for Web Service Endpoints
The container must support the use of Jakarta XML Web Services message handlers for web service endpoints. Container requirements for support of message handlers are specified in [4] and [5].
If message handlers are present, they must be invoked before any business method interceptor methods.
4.10.16. SessionContext
The container must implement the
SessionContext.getEJBObject
method such that the bean instance can use
the Java language cast to convert the returned value to the session
bean’s remote component interface type. Specifically, the bean instance
does not have to use the PortableRemoteObject.narrow
method for the type
conversion.
The container must implement the
EJBContext.lookup
method such that when the lookup
method is used to
look up a bean’s remote home interface, a bean instance can use the Java
language cast to convert the returned value to a session bean’s remote
home interface type. Specifically, the bean instance does not have to
use the PortableRemoteObject.narrow
method for the type conversion.
5. Message-Driven Bean Component Contract
This chapter specifies the contract between a message-driven bean and its container. It defines the life cycle of the message-driven bean instances.
This chapter defines the developer’s view of message-driven bean state management and the container’s responsibility for managing message-driven bean state.
5.1. Overview
A message-driven bean is an asynchronous message consumer. A message-driven bean is invoked by the container as a result of the arrival of a message at the destination or endpoint that is serviced by the message-driven bean. A message-driven bean instance is an instance of a message-driven bean class. A message-driven bean is defined for a single messaging type, in accordance with the message listener interface it employs.
To a client, a message-driven bean is a message consumer that implements some business logic running on the server. A client accesses a message-driven bean by sending messages to the destination or endpoint for which the message-driven bean class is the message listener.
Message-driven beans are anonymous. They have no client-visible identity.
Message-driven bean instances have no conversational state. This means that all bean instances are equivalent when they are not involved in servicing a client message.
A message-driven bean instance is created by the container to handle the processing of the messages for which the message-driven bean is the consumer. Its lifetime is controlled by the container.
A message-driven bean instance has no state for a specific client. However, the instance variables of the message-driven bean instance can contain state across the handling of client messages. Examples of such state include an open database connection and a reference to an enterprise bean.
5.2. Goals
The goal of the message-driven bean model is to make developing an enterprise bean that is asynchronously invoked to handle the processing of incoming messages as simple as developing the same functionality in any other message listener.
A further goal of the message-driven bean model is to allow for the concurrent processing of a stream of messages by means of container-provided pooling of message-driven bean instances.
5.3. Client View of a Message-Driven Bean
To a client, a message-driven bean is simply a message consumer. The client sends messages to the destination or endpoint for which the message-driven bean is the message listener just as it would to any other destination or endpoint. The message-driven bean, as a message consumer, handles the processing of the messages.
From the perspective of the client, the existence of a message-driven bean is completely hidden behind the destination or endpoint for which the message-driven bean is the message listener. The following diagram illustrates the view that is provided to a message-driven bean’s clients.
A client’s JNDI name space may be configured to include the destinations or endpoints of message-driven beans installed in multiple Enterprise Beans containers located on multiple machines on a network. The actual locations of an enterprise bean and Enterprise Beans container are, in general, transparent to the client using the enterprise bean.
References to message destinations can be injected, or they can be looked up in the client’s JNDI namespace.
For example, the reference to the queue for a Jakarta Messaging message-driven bean might be injected as follows.
@Resource
Queue stockInfoQueue;
Alternatively, the queue for the StockInfo
Jakarta Messaging message-driven bean might be located using the following code
segment:
Context initialContext = new InitialContext();
Queue stockInfoQueue = (jakarta.jms.Queue)initialContext.lookup
("java:comp/env/jms/stockInfoQueue");
The remainder of this chapter describes the message-driven bean life cycle in detail and the protocol between the message-driven bean and its container.
5.4. Protocol Between a Message-Driven Bean Instance and its Container
From its creation until destruction, a message-driven bean instance lives in a container. The container provides security, concurrency, transactions, and other services for the message-driven bean. The container manages the life cycle of the message-driven bean instances, notifying the instances when bean action may be necessary, and providing a full range of services to ensure that the message-driven bean implementation is scalable and can support the concurrent processing of a large number of messages.
From the Bean Provider’s point of view, a message-driven bean exists as long as its container does. It is the container’s responsibility to ensure that the message-driven bean comes into existence when the container is started up and that instances of the bean are ready to receive asynchronous message delivery before the delivery of messages is started.
Containers themselves make no actual service demands on the message-driven bean instances. The calls a container makes on a bean instance provide it with access to container services and deliver notifications issued by the container.
Since all instances of a message-driven bean are equivalent, a client message can be delivered to any available instance.
5.4.1. Required MessageDrivenBean Metadata
A message-driven bean must be annotated with
the MessageDriven
annotation or denoted in the deployment descriptor
as a message-driven bean. The MessageDriven
annotation is a
component-defining annotation and is applied to the bean class.
5.4.2. The Required Message Listener Interface
The message-driven bean class must implement
the appropriate message listener interface for the messaging type that
the message-driven bean supports or specify the message listener
interface using the MessageDriven
metadata annotation or the
messaging-type
deployment descriptor element. The specific message
listener interface that is implemented by a message-driven bean class
distinguishes the messaging type that the message-driven bean supports.
The bean’s
message listener method (e.g., onMessage
in the case of
jakarta.jms.MessageListener
) is called by the container when a message
has arrived for the bean to service. The message listener method
contains the business logic that handles the processing of the message.
If the message-driven bean class implements
more than one interface other than java.io.Serializable
,
java.io.Externalizable
, or any of the interfaces defined by the
jakarta.ejb
package, the message listener interface must be specified by
the messageListenerInterface
element of the MessageDriven
annotation
or the messaging-type
element of the message-driven
deployment
descriptor element.
5.4.3. Message-Driven Bean with No-Methods Listener Interface
A message-driven bean is permitted to
implement a listener interface with no methods. A bean that implements a
no-methods interface, exposes all non-static public
methods of the bean
class and of any superclasses except java.lang.Object
as message
listener methods.
In this case, when requested by a resource adapter, the container provides a proxy which implements the message listener interface and all message listener methods of the bean. A resource adapter may use the Reflection API to invoke a message listener method on such a proxy. When the resource adapter invokes a method on the proxy, the message listener method on the bean instance and any interceptor methods are invoked as needed. The resource adapter determines which message listener method is invoked according to its implementation logic.
Only public
methods of the bean class and of
any superclasses except java.lang.Object
may be invoked by a resource
adapter. Attempted invocations of methods with any other access
modifiers on a proxy provided by the container must result in the
jakarta.ejb.EJBException
.
5.4.4. Dependency Injection
A message-driven bean may use dependency
injection mechanisms to acquire references to resources or other objects
in its environment (see Enterprise Bean Environment).
If a message-driven bean makes use of dependency
injection, the container injects these references after the bean
instance is created, and before any message-listener methods are invoked
on the bean instance. If a dependency on the MessageDrivenContext
is
declared, or if the bean class implements the optional
MessageDrivenBean
interface (see The Optional MessageDrivenBean Interface), the
MessageDrivenContext
is also injected at this time.
If dependency injection fails, the bean instance is discarded.
5.4.5. The MessageDrivenContext Interface
If the bean specifies a dependency on the
MessageDrivenContext
interface (or if the bean class implements the
MessageDrivenBean
interface), the container must provide the
message-driven bean instance with a MessageDrivenContext
. This gives
the message-driven bean instance access to the instance’s context
maintained by the container. The MessageDrivenContext
interface has
the following methods:
-
The
setRollbackOnly
method allows the instance to mark the current transaction such that the only outcome of the transaction is a rollback. Only instances of a message-driven bean with container-managed transaction demarcation can use this method. -
The
getRollbackOnly
method allows the instance to test if the current transaction has been marked for rollback. Only instances of a message-driven bean with container-managed transaction demarcation can use this method. -
The
getUserTransaction
method returns thejakarta.transaction.UserTransaction
interface that the instance can use to demarcate transactions, and to obtain transaction status. Only instances of a message-driven bean with bean-managed transaction demarcation can use this method. -
The
getTimerService
method returns thejakarta.ejb.TimerService
interface. -
The
getCallerPrincipal
method returns thejava.security.Principal
that is associated with the invocation. -
The
isCallerInRole
method is inherited from theEJBContext
interface. -
The
getEJBHome
andgetEJBLocalHome
methods are inherited from theEJBContext
interface. Message-driven bean instances must not call these methods. -
The
lookup
method enables the message-driven bean to look up its environment entries in the JNDI naming context. -
The
getContextData
method enables a message listener method, lifecycle callback method, or timeout method to retrieve or update the interceptor context data associated with its invocation.
5.4.6. Message-Driven Bean Lifecycle Callback Interceptor Methods
The following lifecycle event callbacks are supported for message-driven beans.
-
AroundConstruct
-
PostConstruct
-
PreDestroy
The PostConstruct
and PreDestroy
callback
methods may be defined directly on the bean class or on a separate
interceptor class.[36] The AroundConstruct lifecycle
callback interceptor method, if used, must be defined on an interceptor
class (see [15]). See Lifecycle Callback Interceptor Methods.
The PostConstruct
callback occurs before
the first message listener method invocation on the bean. This is at a
point after which any dependency injection has been performed by the
container.
The PostConstruct
lifecycle callback
interceptor method executes in an unspecified transaction and security
context.
The PreDestroy
callback occurs at the time
the bean is removed from the pool or destroyed.
The PreDestroy
lifecycle callback
interceptor method executes in an unspecified transaction and security
context.
5.4.7. The Optional MessageDrivenBean Interface
The message-driven bean class is not required
to implement the jakarta.ejb.MessageDrivenBean
interface.
Compatibility Note: The MessageDrivenBean
interface was
required by earlier versions of the Enterprise Beans specification.
Under the Enterprise Beans 3.x API, the functionality previously provided by the
MessageDrivenBean
interface is available to the bean class through the
use of dependency injection (of the MessageDrivenContext
) and optional
lifecycle callback methods.
The MessageDrivenBean
interface defines two
methods, setMessageDrivenContext
and ejbRemove
.
The setMessageDrivenContext
method is called by the bean’s container to
associate a message-driven bean instance with its context maintained by
the container. Typically a message-driven bean instance retains its
message-driven context as part of its state.
The ejbRemove
notification signals that the
instance is in the process of being removed by the container. In the
ejbRemove
method, the instance releases the resources that it is
holding.
This specification requires that the
ejbRemove
and the ejbCreate
methods of a message-driven bean be
treated as the PreDestroy
and PostConstruct
lifecycle callback
methods, respectively. If the message-driven bean implements the
MessageDrivenBean
interface, the PreDestroy
annotation can only be
applied to the ejbRemove
method. Similar requirements apply to use of
deployment descriptor metadata as an alternative to the use of
annotations.
5.4.8. Timeout Callbacks
A message-driven bean can be registered with the Enterprise Beans Timer Service for time-based event notifications. The container invokes the appropriate bean instance timeout callback method when a timer for the bean has expired. See Timer Service.
5.4.9. Message-Driven Bean Creation
Except as noted
below, the container creates an instance of a message-driven bean in
three steps. First, the container calls the bean class constructor to
create a new message-driven bean instance. Second, the container injects
the bean’s MessageDrivenContext
, if applicable, and performs any
other dependency injection as specified by metadata annotations on the
bean class or by the deployment descriptor. Third, the container calls
the instance’s PostConstruct
lifecycle callback methods, if any. See
Lifecycle Callback Interceptor Methods.
If an interceptor associated with the
message-driven bean declares an AroundConstruct
lifecycle callback
interceptor method, the container follows the rules for the
AroundConstruct
interceptors defined in the Jakarta Interceptors
specification [15].
Compatibility Note: Enterprise Beans 2.1 required the message-driven bean
class to implement the ejbCreate
method. This requirement has been
removed from the Enterprise Beans 3.x API. If the message-driven bean class
implements the ejbCreate
method, the ejbCreate
method is treated as
the bean’s PostConstruct
method, and the PostConstruct
annotation
can only be applied to the ejbCreate
method.
5.4.10. Message Listener Interceptor Methods for Message-Driven Beans
AroundInvoke
interceptor methods are
supported for message-driven beans. These interceptor methods may be
defined on the bean class or on a interceptor class and apply to the
handling of the invocation of the bean’s message listener method(s).
Interceptors are described in Interceptors.
5.4.11. Serializing Message-Driven Bean Methods
The container serializes calls to each message-driven bean instance. Most containers will support many instances of a message-driven bean executing concurrently; however, each instance sees only a serialized sequence of method calls. Therefore, a message-driven bean does not have to be coded as reentrant.
The container must serialize all the container-invoked callbacks (e.g., lifecycle callback interceptor methods and timeout callback methods), and it must serialize these callbacks with the message listener method calls.
5.4.12. Concurrency of Message Processing
A container allows many instances of a message-driven bean class to be executing concurrently, thus allowing for the concurrent processing of a stream of messages. No guarantees are made as to the exact order in which messages are delivered to the instances of the message-driven bean class, although the container should attempt to deliver messages in order when it does not impair the concurrency of message processing. Message-driven beans should therefore be prepared to handle messages that are out of sequence: for example, the message to cancel a reservation may be delivered before the message to make the reservation.
5.4.13. Transaction Context of Message-Driven Bean Methods
A bean’s message
listener and timeout callback methods are invoked in the scope of a
transaction determined by the transaction attribute specified in the
bean’s metadata annotations or deployment descriptor. If the bean is
specified as using container-managed transaction demarcation, either the
REQUIRED
or the NOT_SUPPORTED
transaction attribute must be used for
the message listener methods, and either the REQUIRED
, REQUIRES_NEW
,
or the NOT_SUPPORTED
transaction attribute for timeout callback
methods. See Support for Transactions.
When a message-driven bean using bean-managed
transaction demarcation uses the jakarta.transaction.UserTransaction
interface to demarcate transactions, the message receipt that causes the
bean to be invoked is not part of the transaction. If the message
receipt is to be part of the transaction, container-managed transaction
demarcation with the REQUIRED
transaction attribute must be used.
The bean constructor, the
setMessageDrivenContext
method, the message-driven bean’s dependency
injection methods, and lifecycle callback methods are called with an
unspecified transaction context. Refer to Handling of Methods that Run with "an unspecified transaction context" for how the
container executes methods with an unspecified transaction context.
5.4.14. Security Context of Message-Driven Bean Methods
A caller principal may propagate into a message-driven bean’s message listener methods. Whether this occurs is a function of the specific message-listener interface and associated messaging provider, but is not governed by this specification.
The Bean Provider can use the RunAs
metadata
annotation (or corresponding deployment descriptor element) to define a
run-as identity for the enterprise bean. The run-as identity applies to
the bean’s message listener methods and timeout methods. Run-as identity
behavior is further defined in Run-as.
5.4.15. Association of a Message-Driven Bean with a Destination or Endpoint
A message-driven bean is associated with a destination or endpoint when the bean is deployed in the container. It is the responsibility of the Deployer to associate the message-driven bean with a destination or endpoint.
5.4.16. Activation Configuration Properties
The Bean Provider may provide information to the Deployer about the configuration of the message-driven bean in its operational environment. This may include information about message acknowledgement modes, message selectors, expected destination or endpoint types, etc.
Activation configuration properties are
specified by means of the activationConfig
element of the
MessageDriven
annotation or activation-config
deployment descriptor
element. Activation configuration properties specified in the deployment
descriptor are added to those specified by means of the MessageDriven
annotation. If a property of the same name is specified in both, the
deployment descriptor value overrides the value specified in the
annotation.
5.4.17. Jakarta Messaging Message-Driven Beans
This section describes activation configuration properties specific to the Jakarta Messaging message-driven beans.
The container may or may not support its built-in Jakarta Messaging provider using a resource adapter. However, it must allow the application to configure a message-driven bean that uses the built-in Jakarta Messaging provider using the activation properties defined by this specification.
Both the container and any Jakarta Messaging resource adapters are free to support activation properties in addition to those listed here. However, applications that use non-standard activation properties will not be portable.
5.4.17.1. Message Acknowledgment
Jakarta Messaging
message-driven beans should not attempt to use the Jakarta Messaging API for message
acknowledgment. Message acknowledgment is automatically handled by the
container. If the message-driven bean uses container-managed transaction
demarcation, message acknowledgment is handled automatically as a part
of the transaction commit. If bean-managed transaction demarcation is
used, the message receipt cannot be part of the bean-managed
transaction, and, in this case, the receipt is acknowledged by the
container. If bean-managed transaction demarcation is used, the Bean
Provider can indicate whether Jakarta Messaging AUTO_ACKNOWLEDGE
semantics or
DUPS_OK_ACKNOWLEDGE
semantics should apply by using the
activationConfig
element of the MessageDriven
annotation or by using
the activation-config-property
deployment descriptor element. The
property name used to specify the acknowledgment mode is
acknowledgeMode
. If the acknowledgeMode
property is not specified,
Jakarta Messaging AUTO_ACKNOWLEDGE
semantics are assumed. The value of the
acknowledgeMode
property must be either Auto-acknowledge
or
Dups-ok-acknowledge
for a Jakarta Messaging message-driven bean.
5.4.17.2. Message Selectors
The Bean Provider may declare the Jakarta Messaging message
selector to be used in determining which messages a Jakarta Messaging message-driven
bean is to receive. If the Bean Provider wishes to restrict the messages
that a Jakarta Messaging message-driven bean receives, the Bean Provider can specify
the value of the message selector by using the activationConfig
element of the MessageDriven
annotation or by using the
activation-config-property
deployment descriptor element. The property
name used to specify the message selector is messageSelector
.
For example:
@MessageDriven(activationConfig={
@ActivationConfigProperty(
propertyName="messageSelector",
propertyValue="JMSType = 'car' AND color = 'blue'
AND weight > 2500")
})
<activation-config>
<activation-config-property>
<activation-config-property-name>
messageSelector
</activation-config-property-name>
<activation-config-property-value>
JMSType = 'car' AND color = 'blue' AND
weight > 2500
</activation-config-property-value>
</activation-config-property>
</activation-config>
The Application Assembler may further
restrict, but not replace, the value of the messageSelector
property
of a Jakarta Messaging message-driven bean.
5.4.17.3. Destination Type
A Jakarta Messaging message-driven bean is associated with a Jakarta Messaging Destination (Queue or Topic) when the bean is deployed in the container. It is the responsibility of the Deployer to associate the message-driven bean with a Queue or Topic.
The Bean Provider may provide advice to the
Deployer as to whether a message-driven bean is intended to be
associated with a Queue or a Topic by using the activationConfig
element of the MessageDriven
annotation or by using the
activation-config-property
deployment descriptor element. The property
name used to specify the destination type associated with the bean is
destinationType
. The value for this property must be either
jakarta.jms.Queue
or jakarta.jms.Topic
for a Jakarta Messaging message-driven bean.
5.4.17.4. Destination Lookup
The Bean Provider or Deployer may specify the Jakarta Messaging queue or topic from which a Jakarta Messaging message-driven bean is to receive messages.
The lookup name of an administratively-defined Queue
or Topic
object may be specified by using the activationConfig
element of
the MessageDriven
annotation or by using
the activation-config-property
deployment descriptor element. The
property name used to specify the lookup name is destinationLookup
.
5.4.17.5. Connection Factory Lookup
The Bean Provider or Deployer may specify the Jakarta Messaging connection factory that will be used to connect to the Jakarta Messaging provider from which a Jakarta Messaging message-driven bean is to receive messages.
The lookup name of an administratively-defined ConnectionFactory
object may be specified by using the activationConfig
element of
the MessageDriven
annotation or by using
the activation-config-property
deployment descriptor element. The
property name used to specify the lookup name is
connectionFactoryLookup
.
5.4.17.6. Subscription Durability
If the
message-driven bean is intended to be used with a topic, the Bean
Provider may further indicate whether a durable or non-durable
subscription should be used by using the activationConfig
element of
the MessageDriven
annotation or by using the
activation-config-property
deployment descriptor element. The property
name used to specify whether a durable or non-durable subscription
should be used is subscriptionDurability
. The value for this property
must be either Durable
or NonDurable
for a Jakarta Messaging message-driven bean.
If a topic subscription is specified and subscriptionDurability
is not
specified, a non-durable subscription is assumed.
-
Durable topic subscriptions, as well as queues, ensure that messages are not missed even if the Enterprise Beans server is not running. Reliable applications will typically make use of queues or durable topic subscriptions rather than non-durable topic subscriptions.
-
If a non-durable topic subscription is used, it is the container’s responsibility to make sure that the message-driven bean subscription is active (i.e., that there is a message-driven bean available to service the message) in order to ensure that messages are not missed as long as the Enterprise Beans server is running. Messages may be missed, however, when a bean is not available to service them. This will occur, for example, if the Enterprise Beans server goes down for any period of time.
The Deployer should avoid associating more than one message-driven bean with the same Jakarta Messaging queue. If there are multiple Jakarta Messaging consumers for a queue, Jakarta Messaging does not define how messages are distribued between the queue receivers.
5.4.17.7. Subscription Name
If the message-driven bean is intended to be
used with a topic, and the bean provider has indicated that a durable
subscription should be used by specifying the subscriptionDurability
property to Durable
, then the bean provider or deployer may specify the
name of the durable subscription.
The name of the subscription may be specified
by using the activationConfig
element of the MessageDriven
annotation or by using the activation-config-property
deployment
descriptor element. The property name used to specify the name of the subscription is subscriptionName
.
The Bean Provider or Deployer cannot specify whether a shared or unshared subscription will be used.
5.4.17.8. Client Identifier
The Bean Provider or Deployer may specify the Jakarta Messaging client identifier that will be used when connecting to the Jakarta Messaging provider from which a Jakarta Messaging message-driven bean is to receive messages.
The client identifier may be specified by
using the activationConfig
element of the MessageDriven
annotation
or by using the activation-config-property
deployment descriptor
element. The property name used to specify the client identifier is
clientId
.
5.4.18. Dealing with Exceptions
A message-driven bean’s message listener
method must not throw the java.rmi.RemoteException
.
Message-driven beans should not, in general,
throw RuntimeException
.
A RuntimeException
that is not an application
exception thrown from any method of the message-driven bean class
(including a message listener method and the callbacks invoked by the
container) results in the transition to the "does not exist" state. If a
message-driven bean uses bean-managed transaction demarcation and throws
a RuntimeException
, the container should not acknowledge the message.
Exception handling is described in detail in Exception Handling. See the
Jakarta Interceptors specification [15] for the
rules pertaining to lifecycle callback interceptor methods when more
than one such method applies to the bean class.
From the client perspective, the message consumer continues to exist. If the client continues sending messages to the destination or endpoint associated with the bean, the container can delegate the client’s messages to another instance.
The message listener methods of some messaging types may throw application exceptions. An application exception is propagated by the container to the resource adapter.
5.4.19. Missed PreDestroy Callbacks
The Bean Provider
cannot assume that the container will always invoke the PreDestroy
callback method (or ejbRemove
method) for a message-driven bean
instance. The following scenarios result in the PreDestroy callback
method not being called on an instance:
-
A crash of the Enterprise Beans container.
-
A system exception thrown from the instance’s method to the container.
If the message-driven bean instance allocates
resources in the PostConstruct
lifecycle callback method and/or in the
message listener method, and releases normally the resources in the
PreDestroy
method, these resources will not be automatically released
in the above scenarios. The application using the message-driven bean
should provide some clean up mechanism to periodically clean up the
unreleased resources.
5.4.20. Replying to a Jakarta Messaging Message
In standard Jakarta Messaging usage scenarios, the
messaging mode of a message’s JMSReplyTo
destination (Queue or Topic) is the same as the mode of the destination
to which the message has been sent. Although a message-driven bean is
not directly dependent on the mode of the Jakarta Messaging destination from which it
is consuming messages, it may contain code that depends on the mode of
its message’s JMSReplyTo
destination. In particular, if a
message-driven bean replies to a message,
the mode of the reply’s message producer and the mode of the
JMSReplyTo
destination must be the same. In order to implement a
message-driven bean that is independent of JMSReplyTo
mode, the Bean
Provider should use instanceOf
to test whether a JMSReplyTo
destination is a Queue or Topic, and then use a matching message
producer for the reply.
5.5. Message-Driven Bean State Diagram
When a client sends a message to a Destination for which a message-driven bean is the consumer, the container selects one of its method-ready instances and invokes the instance’s message listener method.
The following figure illustrates the life cycle of a message-driven bean instance.
The following steps describe the life cycle of a message-driven bean instance:
A message-driven bean instance’s life starts
when the container invokes the message-driven bean class constructor to
create a new instance.[37]
Next, the container
injects the bean’s MessageDrivenContext
object, if applicable, and
performs any other dependency injection as specified by metadata
annotations on the bean class or by the deployment descriptor. The
container then calls the bean’s PostConstruct
lifecycle callback
methods, if any.
The message-driven bean instance is now ready to be delivered a message sent to its associated destination or endpoint by any client or a call from the container to a timeout callback method.
When the container no longer needs the
instance (which usually happens when the container wants to reduce the
number of instances in the method-ready pool), the container invokes the
PreDestroy
lifecycle callback methods for it, if any. This ends the
life of the message-driven bean instance.
5.5.1. Operations Allowed in the Methods of a Message-Driven Bean Class
Operations Allowed in the Methods of a Message-Driven Bean defines the methods of
a message-driven bean class in which the message-driven bean instances
can access the methods of the jakarta.ejb.MessageDrivenContext
interface,
the java:comp/env
environment naming context, resource managers,
TimerService
and Timer
methods, the EntityManager
and
EntityManagerFactory
methods, and other enterprise beans.
If a
message-driven bean instance attempts to invoke a method of the
MessageDrivenContext
interface, and the access is not allowed in
Operations Allowed in the Methods of a Message-Driven Bean, the container must throw and log the
java.lang.IllegalStateException
.
If a message-driven bean instance attempts to
invoke a method of the TimerService
or Timer
interface, and the
access is not allowed in Operations Allowed in the Methods of a Message-Driven Bean, the
container must throw the java.lang.IllegalStateException
.
If a bean instance attempts to access a resource manager, an enterprise bean, or an entity manager or entity manager factory, and the access is not allowed in Operations Allowed in the Methods of a Message-Driven Bean, the behavior is undefined by the Enterprise Beans specification.
Bean method | Bean method can perform the following operations | |
---|---|---|
Container-managed transaction demarcation |
Bean-managed transaction demarcation |
|
constructor |
- |
- |
dependency injection methods (e.g., setMessageDrivenContext) |
JNDI access to java:comp/env |
JNDI access to java:comp/env |
PostConstruct, PreDestroy lifecycle callback methods |
JNDI access to java:comp/env |
JNDI access to java:comp/env |
message listener method, AroundInvoke interceptor method |
JNDI access to java:comp/env |
UserTransaction methods |
timeout callback method |
JNDI access to java:comp/env |
UserTransaction methods |
Additional restrictions:
-
The
getRollbackOnly
andsetRollbackOnly
methods of theMessageDrivenContext
interface should be used only in the message-driven bean methods that execute in the context of a transaction. The container must throw thejava.lang.IllegalStateException
if the methods are invoked while the instance is not associated with a transaction.
The reasons for disallowing operations in Operations Allowed in the Methods of a Message-Driven Bean:
-
Invoking the getRollbackOnly and setRollbackOnly methods is disallowed in the message-driven bean methods for which the container does not have a meaningful transaction context, and for all message-driven beans with bean-managed transaction demarcation.
-
The
UserTransaction
interface is unavailable to message-driven beans with container-managed transaction demarcation. -
Invoking
getEJBHome
orgetEJBLocalHome
is disallowed in message-driven bean methods because there are no EJBHome or EJBLocalHome objects for message-driven beans. The container must throw and log thejava.lang.IllegalStateException
if these methods are invoked.
5.6. The Responsibilities of the Bean Provider
This section describes the responsibilities of the message-driven Bean Provider to ensure that a message-driven bean can be deployed in any Enterprise Beans container.
5.6.1. Classes and Interfaces
The message-driven Bean Provider is responsible for providing the following class files:
-
Message-driven bean class.
-
Interceptor classes, if any.
5.6.2. Message-Driven Bean Class
The following are the requirements for the message-driven bean class:
-
The class must implement, directly or indirectly, the message listener interface required by the messaging type that it supports or the methods of the message listener interface. In the case of Jakarta Messaging, this is the
jakarta.jms.MessageListener
interface. -
The class must be defined as
public
, must not befinal
, and must not beabstract
. The class must be a top level class. -
The class must have a
public
constructor that takes no arguments. The container uses this constructor to create instances of the message-driven bean class. -
The class must not define the
finalize
method.
Optionally:
-
The class may implement, directly or indirectly, the
jakarta.ejb.MessageDrivenBean
interface. -
The class may implement, directly or indirectly, the
jakarta.ejb.TimedObject
interface. -
The class may implement the
ejbCreate
method. -
The class may have an additional constructor annotated with the
Inject
annotation (see Relationship to Jakarta Contexts and Dependency Injection and the CDI specification [8]).
The message-driven bean class may have
superclasses and/or superinterfaces. If the message-driven bean has
superclasses, the message listener methods, lifecycle callback
interceptor methods, timeout callback methods, the ejbCreate
method,
and the methods of the MessageDrivenBean
interface may be defined in
the message-driven bean class or in any of its superclasses.
The message-driven bean class is allowed to implement other methods (for example, helper methods invoked internally by the message listener method) in addition to the methods required by the Enterprise Beans specification.
5.6.3. Message-Driven Bean Superclasses
A message-driven bean class is permitted to have superclasses that are themselves message-driven bean classes. However, there are no special rules that apply to the processing of annotations or the deployment descriptor for this case. For the purposes of processing a particular message-driven bean class, all superclass processing is identical regardless of whether the superclasses are themselves message-driven bean classes. In this regard, the use of message-driven bean classes as superclasses merely represents a convenient use of implementation inheritance, but does not have component inheritance semantics.
5.6.4. Message Listener Method
The message-driven bean class must define the message listener methods. The signature of a message listener method must follow these rules:
The method must be declared as public
.
The method must not be declared as final
or static
.
5.6.5. Message-Driven Bean with No-Methods Listener Interface
The following additional requirements apply for a message-driven bean with a no-methods interface:
-
All non-static
public
methods of the bean class and of any superclasses exceptjava.lang.Object
are exposed as message listener methods.
Note: This includes callback methods. The Bean Provider should exercise caution when choosing to expose callback methods as message listener methods. The runtime context (e.g. transaction context, caller principal, operations allowed, etc.) for a method invoked as a callback can differ significantly from the context for the same method when invoked as a message listener. In general, callback methods should not be exposed as message listener methods. Therefore, it is recommended that all methods other than message listener methods be assigned an access type other than public.
-
Only private methods of the bean class and any superclasses except
java.lang.Object
may be declaredfinal
.
5.6.6. Lifecycle Callback Interceptor Methods
PostConstruct
and PreDestroy
lifecycle callback interceptor methods may be defined for message-driven
beans. If PrePassivate
or PostActivate
lifecycle callbacks are
defined, they are ignored.[38]
Compatibility Note: If the PostConstruct
lifecycle callback
interceptor method is the ejbCreate
method, or if the PreDestroy
lifecycle callback interceptor method is the ejbRemove
method, these
callback methods must be implemented on the bean class itself (or on its
superclasses). Except for these cases, the method names can be
arbitrary, but must not start with "ejb" to avoid conflicts with the
callback methods defined by the jakarta.ejb.EnterpriseBean
interfaces.
Lifecycle callback interceptor methods may be defined on the bean class and/or on an interceptor class of the bean. Rules applying to the definition of lifecycle callback interceptor methods are defined in Interceptors for LifeCycle Event Callbacks.
5.7. The Responsibilities of the Container Provider
This section describes the responsibilities of the Container Provider to support a message-driven bean. The Container Provider is responsible for providing the deployment tools, and for managing the message-driven bean instances at runtime.
Because the Enterprise Beans specification does not define the API between deployment tools and the container, we assume that the deployment tools are provided by the Container Provider. Alternatively, the deployment tools may be provided by a different vendor who uses the container vendor’s specific API.
5.7.1. Generation of Implementation Classes
The deployment tools provided by the container are responsible for the generation of additional classes when the message-driven bean is deployed. The tools obtain the information that they need for generation of the additional classes by introspecting the classes and interfaces provided by the Enterprise Bean Provider and by examining the message-driven bean’s deployment descriptor.
The deployment tools may generate a class that mixes some container-specific code with the message-driven bean class. This code may, for example, help the container to manage the bean instances at runtime. Subclassing, delegation, and code generation can be used by the tools.
5.7.2. Deployment of Message-Driven Beans with No-Methods Listener Interface
The Container Provider must support the deployment of a message-driven bean with a no-methods listener interface.
The container’s implementation class
generated by the deployment tools must implement the message listener
interface and implement all non-static public
methods of the bean class
and of any superclasses except java.lang.Object
as message listener
methods.
5.7.3. Deployment of Jakarta Messaging Message-Driven Beans
The Container Provider must support the deployment of a Jakarta Messaging message-driven bean as the consumer of a Jakarta Messaging queue or topic.
5.7.4. Request/Response Messaging Types
If the message listener supports a request/response messaging type, it is the container’s responsibility to deliver the message response.
5.7.5. Non-reentrant Instances
The container must ensure that only one thread can be executing an instance at any time.
5.7.6. Transaction Scoping, Security, Exceptions
The container must follow the rules with respect to transaction scoping, security checking, and exception handling, as described in Support for Transactions, Security Management, and Exception Handling.
6. Persistence
The model for persistence and object/relational mapping was considerably revised and enhanced in the Enterprise Beans 3.0 release. The contracts and requirements for persistent entities are defined by the "Jakarta Persistence" specification [3], which also contains the full specification of the Jakarta Persistence query language and the metadata for object/relational mapping.
The client view of entity beans under the earlier Enterprise Beans 2.1 programming model, the contracts for Enterprise Beans 2.1 Entity Beans with Container-Managed Persistence, the contracts for the Enterprise Beans QL query language, the contracts for Enterprise Beans 2.1 Entity Beans with Bean-Managed Persistence, and the contracts for Enterprise Beans 1.1 Entity Beans with Container-Managed Persistence are described in the Enterprise Beans Optional Features document [2]. See Chapter 3, Chapter 4, Chapter 5, Chapter 6 and Chapter 7 respectively.
7. Interceptors
Interceptors are used to interpose on the business method invocations and lifecycle events that occur on an enterprise bean instance.
7.1. Overview
The general rules for defining Interceptor classes, their lifecycle, and associated metadata are described in the Jakarta Interceptors specification [15]. This chapter describes the set of requirements that are specific to the use of interceptors with Enterprise Beans.
For the use of interceptors with Enterprise Beans, the interceptor "target class" is the bean class. Interceptors may be used with session beans and message-driven beans.
The programming restrictions that apply to enterprise bean components apply to interceptors as well. See Programming Restrictions.
It is illegal to associate Jakarta Transactions transactional interceptors (see [17]) with Enterprise Beans. The Enterprise Beans Container should fail deployment of such applications.[39]
Default interceptors are interceptors that
apply to all components within an ejb-jar file or .war
file.
7.2. Interceptor Life Cycle
The lifecycle of an interceptor instance is the same as that of the bean instance with which it is associated. In the case of interceptors associated with stateful session beans, the interceptor instances are passivated upon bean instance passivation, and activated when the bean instance is activated. See Stateful Session Beans, Stateless Session Bean Lifecycle State Diagram, and Message-Driven Bean State Diagram.
In addition to the AroundConstruct
,
PostConstruct
and PreDestroy
callback support required by the
Jakarta Interceptors specification [15],
interceptors associated with stateful session beans may define
PostActivate
and PrePassivate
callbacks. Both the interceptor instance
and the bean instance are created or activated before any of the
respective PostConstruct
or PostActivate
callbacks are invoked. Any
PreDestroy
and PrePassivate
callbacks are invoked before the
respective destruction or passivation of either the bean instance or
interceptor instance.
The use of an extended persistence context is only supported for interceptors that are associated with stateful session beans.
7.3. Business Method Interceptors
AroundInvoke
interceptor methods may be
defined for business methods of sessions beans and for the message
listener methods of message-driven beans.
Business method interceptor methods may throw
runtime exceptions or application exceptions that are allowed in the
throws
clause of the business method. See section
Exception Handling for further details.
7.4. Timer Timeout Method Interceptors
Interceptor methods may be defined for the
Enterprise Beans timer timeout methods of session beans and message-driven beans.
Such methods are referred to as AroundTimeout
methods.
Within an AroundTimeout
method, the
InvocationContext.getTimer()
method returns the jakarta.ejb.Timer
object associated with the timeout being intercepted.
AroundTimeout
methods may throw system exceptions, but not
application exceptions. See Exception Handling for further details.
7.5. Interceptors for LifeCycle Event Callbacks
Lifecycle callback interceptor methods may be defined for session beans and message-driven beans.
The AroundConstruct
, PostConstruct
,
PreDestroy
, PostActivate
, and PrePassivate
annotations are used
to define interceptor methods for a lifecycle callback events. An
AroundConstruct
lifecycle callback interceptor method may be defined on
an interceptor class only. All other interceptor methods can be defined
on an interceptor class and/or directly on the bean class.
Lifecycle callback interceptor methods are
invoked in an unspecified security context. Lifecycle callback
interceptor methods are invoked in an unspecified transaction context,
except for singleton and stateful session bean PostConstruct
and
PreDestroy
methods and stateful session bean PostActivate
, and
PrePassivate
methods, whose transaction context is based on their
respective transaction attributes. See Session Bean Lifecycle Callback Interceptor Methods.
PostActivate
, and PrePassivate
methods
follow requirements for the lifecycle callback interceptor methods
defined in the Interceptors specification document [15].
Lifecycle callback interceptor methods may throw system runtime exceptions, but not application exceptions. See Exception Handling for further details.
7.6. InvocationContext
The InvocationContext
object provides
metadata that enables interceptor methods to control the behavior of the
invocation chain. The getContextData
method enables an interceptor to
retrieve or update the data associated with the invocation by another
interceptor, business method, and/or webservices context in the
invocation chain. The contextual data is not sharable across separate
business method invocations or lifecycle callback events. If
interceptors are invoked as a result of the invocation on a web service
endpoint, the map returned by the getContextData
method will be the
Jakarta XML Web Services MessageContext
[4]. The lifecycle of the
InvocationContext
instance is otherwise unspecified.
7.7. Exception Handling
Interceptor methods are allowed to throw
runtime exceptions or any checked exceptions that the method they
interpose on allows within its throws
clause. Interceptor methods
are allowed to catch and suppress exceptions and recover by calling
proceed()
.
Interceptor method invoked in a
transaction context, can mark the transaction for rollback by throwing a
runtime exception or by calling the EJBContext
method
setRollbackOnly()
. This may be done before or after
InvocationContext.proceed()
is called.
If a system exception escapes the interceptor
chain, the bean instance and any associated interceptor instances are
discarded (unless the bean is a singleton session
bean [40]). The PreDestroy
callbacks are not invoked
in this case: the interceptor methods in the chain should perform any
necessary clean-up operations as the interceptor chain unwinds.
7.8. Specification of Interceptors in the Deployment Descriptor
The deployment descriptor can be used as an alternative to metadata annotations to specify interceptors and their binding to enterprise beans or to override the invocation order of interceptors as specified in annotations.
7.8.1. Specification of Interceptors
The interceptor
deployment descriptor
element is used to specify the interceptor methods of an interceptor
class. The interceptor methods are specified by using the
around-invoke
, around-timeout
, around-construct
,
post-construct
, pre-destroy
, pre-passivate
, and post-activate
elements.
At most one method of a given interceptor class can be designated as an around-invoke method, an around-timeout method, a lifecycle callback interceptor method, regardless of whether the deployment descriptor is used to define interceptors or whether some combination of annotations and deployment descriptor elements is used.
7.8.2. Binding of Interceptors to Target Classes
The interceptor-binding
element is used to
specify the binding of interceptor classes to target classes and their
methods. The subelements of the interceptor-binding
element are as
follows:
-
The
target-name
element must identify the associated target class or the wildcard value"*"
(which is used to define interceptors that are bound to all target classes). -
The
interceptor-class
element specifies the interceptor class. The interceptor class contained in aninterceptor-class
element must either be declared in theinterceptor
deployment descriptor element or appear in at least oneInterceptor
annotation on a target class. Theinterceptor-order
element is used as an optional alternative to specify a total ordering over the interceptors defined for the given level and above. -
The
exclude-default-interceptors
andexclude-class-interceptors
elements specify that default interceptors and class interceptors, respectively, are not to be applied to a target class and/or method. -
The
method-name
element specifies the method name for a method-level interceptor; and the optionalmethod-params
elements identify a single method among multiple methods with an overloaded method name. -
The
method-name
element may be used to bind a constructor-level interceptor using the unqualified name of the bean class as the value; the optionalmethod-params
elements identify the constructor if a bean class has a constructor annotated with theInject
annotation in addition to a no-arg constructor.
Default interceptors are bound to all target
classes in a module using the wildcard syntax "*"
. In addition,
interceptors may be bound at the level of the target class (class-level
interceptors) or methods of the target class (method-level
interceptors).
The binding of interceptors to classes is
additive. If interceptors are bound at the class level and/or default
level as well as at the method level, both class-level and/or
default-level as well as method-level interceptors will apply. The
deployment descriptor may be used to augment the interceptors and
interceptor methods defined by means of annotations. When the deployment
descriptor is used to augment the interceptors specified in annotations,
the interceptor methods specified in the deployment descriptor will be
invoked after those specified in annotations, according to the ordering
specified earlier. The interceptor-order
deployment descriptor element
may be used to override this ordering.
The exclude-default-interceptors
element
disables default interceptors for the level at which it is specified and
lower. That is, exclude-default-interceptors
when applied at the class
level disables the application of default interceptors for all methods
of the class. The exclude-class-interceptors
element applied to a
method disables the application of class-level interceptors for the
given method. Explicitly listing an excluded higher-level interceptor at
a lower level causes it to be applied at that level and below.
It is possible to override the ordering of
interceptors by using the interceptor-order
element to specify a total
ordering of interceptors at class level and/or method level. If the
interceptor-order
element is used, the ordering specified at the given
level must be a total order over all interceptor classes that have been
defined at that level and above (unless they have been explicitly
excluded by means of one of the exclude-
elements described above).
There are four possible styles of the
interceptor-binding
element syntax:
Style 1:
<interceptor-binding>
<target-name>*</target-name>
<interceptor-class>INTERCEPTOR</interceptor-class>
</interceptor-binding>
Specifying the target-name
element as the
wildcard value "*"
designates default interceptors.
Style 2:
<interceptor-binding>
<target-name>TARGETNAME</target-name>
<interceptor-class>INTERCEPTOR</interceptor-class>
</interceptor-binding>
This style is used to refer to interceptors associated with the specified target class (class-level interceptors).
Style 3:
<interceptor-binding>
<target-name>TARGETNAME</target-name>
<interceptor-class>INTERCEPTOR</interceptor-class>
<method-name>METHOD</method-name>
</interceptor-binding>
This style is used to associate a
method-level interceptor with the specified method of the specified
target class. If there are multiple methods with the same overloaded
name, the element of this style refers to all the methods with the
overloaded name. Note that the wildcard value "*"
cannot be used to
specify method-level interceptors.
Style 4:
<interceptor-binding>
<target-name>TARGETNAME</target-name>
<interceptor-class>INTERCEPTOR</interceptor-class>
<method-name>METHOD</method-name>
<method-params>
<method-param>PARAM-1</method-param>
<method-param>PARAM-2</method-param>
...
<method-param>PARAM-n</method-param>
</method-params>
<interceptor-binding>
This style is used to associate a
method-level interceptor with the specified method of the specified
target class. This style is used to refer to a single method within a
set of methods with an overloaded name. The values PARAM-1
through
PARAM-n
are the fully-qualified Java types of the method’s input
parameters (if the method has no input arguments, the method-params
element contains no method-param
elements). Arrays are specified by
the array element’s type, followed by one or more pair of square
brackets (e.g. int[][]
).
If both styles 3 and 4 are used to define method-level interceptors for the same bean, the relative ordering of those method-level interceptors is undefined.
7.8.2.1. Examples
Examples of the usage of the
interceptor-binding
syntax are given below.
Style 1: The following interceptors are default interceptors. They will be invoked in the order specified.
<interceptor-binding>
<target-name>*</target-name>
<interceptor-class>org.acme.MyDefaultIC</interceptor-class>
<interceptor-class>org.acme.MyDefaultIC2</interceptor-class>
</interceptor-binding>
Style 2: The following interceptors are
the class-level interceptors of the EmployeeService
class. They will
be invoked in the order specified after any default interceptors.
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-class>org.acme.MyIC</interceptor-class>
<interceptor-class>org.acme.MyIC2</interceptor-class>
</interceptor-binding>
Style 3: The following interceptors apply
to all the myMethod
methods of the EmployeeService
class. They will
be invoked in the order specified after any default interceptors and
class-level interceptors.
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-class>org.acme.MyIC</interceptor-class>
<interceptor-class>org.acme.MyIC2</interceptor-class>
<method-name>myMethod</method-name>
</interceptor-binding>
The following example illustrates more
complex parameter types. The method myMethod(char s, int i,
int[] iar, mypackage.MyClass mycl, mypackage.MyClass[][]
myclaar)
would be specified as:
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-class>org.acme.MyIC</interceptor-class>
<method-name>myMethod</method-name>
<method-params>
<method-param>char</method-param>
<method-param>int</method-param>
<method-param>int[]</method-param>
<method-param>mypackage.MyClass</method-param>
<method-param>mypackage.MyClass[][]</method-param>
</method-params>
</interceptor-binding>
The following example illustrates
constructor-level interceptors that apply to all constructors of the
EmployeeService
class. They will be invoked in the order specified
after any default interceptors and class-level interceptors.
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-class>org.acme.MyIC</interceptor-class>
<interceptor-class>org.acme.MyIC2</interceptor-class>
<method-name>EmployeeService</method-name>
</interceptor-binding>
Style 4: The following interceptor
element refers to the myMethod(String firstName, String LastName)
method of the EmployeeService
class.
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-class>org.acme.MyIC</interceptor-class>
<method-name>myMethod</method-name>
<method-params>
<method-param>java.lang.String</method-param>
<method-param>java.lang.String</method-param>
</method-params>
</interceptor-binding>
The following example illustrates
constructor-level interceptors that apply to the specific constructor of
the EmployeeService
class.
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-class>org.acme.MyIC</interceptor-class>
<interceptor-class>org.acme.MyIC2</interceptor-class>
<method-name>EmployeeService</method-name>
<method-params>
<method-param>org.acme.Account</method-param>
<method-param>java.lang.String</method-param>
</method-params>
</interceptor-binding>
The following example illustrates the total
ordering of interceptors using the interceptor-order
element:
<interceptor-binding>
<target-name>EmployeeService</target-name>
<interceptor-order>
<interceptor-class>org.acme.MyIC
</interceptor-class>
<interceptor-class>org.acme.MyDefaultIC
</interceptor-class>
<interceptor-class>org.acme.MyDefaultIC2
</interceptor-class>
<interceptor-class>org.acme.MyIC2
</interceptor-class>
</interceptor-order>
</interceptor-binding>
8. Support for Transactions
One of the key features of the Enterprise Beans architecture is support for distributed transactions. The Enterprise Beans architecture allows an application developer to write an application that atomically updates data in multiple databases which may be distributed across multiple sites. The sites may use Enterprise Beans servers from different vendors.
8.1. Overview
This section provides a brief overview of transactions and illustrates a number of transaction scenarios in Enterprise Beans.
8.1.1. Transactions
Transactions are a proven technique for simplifying application programming. Transactions free the application programmer from dealing with the complex issues of failure recovery and multi-user programming. The transactional system ensures that a unit of work either fully completes, or the work is fully rolled back. Furthermore, transactions make it possible for the programmer to design the application as if it ran in an environment that executes units of work serially.
Support for transactions is an essential element of the Enterprise Beans architecture. The Enterprise Bean Provider and the client application programmer are not exposed to the complexity of distributed transactions. The Bean Provider can choose between using programmatic transaction demarcation in the enterprise bean code (this style is called bean-managed transaction demarcation) or declarative transaction demarcation performed automatically by the Enterprise Beans container (this style is called container-managed transaction demarcation).
With bean-managed
transaction demarcation, the enterprise bean code demarcates
transactions using the jakarta.transaction.UserTransaction
interface. All
resource manager accesses between the UserTransaction.begin
and
UserTransaction.commit
calls are part of a transaction.
With container-managed transaction demarcation, the container demarcates transactions per instructions provided by the developer in metadata annotations or in the deployment descriptor. These instructions, called transaction attributes, tell the container whether it should include the work performed by an enterprise bean method in a client’s transaction, run the enterprise bean method in a new transaction started by the container, or run the method with "no transaction" (Refer to Handling of Methods that Run with "an unspecified transaction context" for the description of the "no transaction" case).
Regardless of whether an enterprise bean uses bean-managed or container-managed transaction demarcation, the burden of implementing transaction management is on the Enterprise Beans Container and Server Provider. The Enterprise Beans container and server implement the necessary low-level transaction protocols, such as the two-phase commit protocol between a transaction manager and a database system or messaging provider, transaction context propagation, and distributed two-phase commit.
Many applications will consist of one or several enterprise beans that all use a single resource manager (typically a relational database management system). The Enterprise Beans container can make use of resource manager local transactions as an optimization technique for enterprise beans for which distributed transactions are not needed. A resource manager local transaction does not involve control or coordination by an external transaction manager. The container’s use of local transactions as an optimization technique for enterprise beans with either container-managed transaction demarcation or bean-managed transaction demarcation is not visible to the enterprise beans. For a discussion of the use of resource manager local transactions as a container optimization strategy, refer to [18] and [16].
8.1.2. Transaction Model
The Enterprise Beans architecture supports flat transactions. A flat transaction cannot have any child (nested) transactions.
8.1.3. Relationship to Jakarta Transactions
The Jakarta® Transactions [17] is a specification of the interfaces between a transaction manager and the other parties involved in a distributed transaction processing system: the application programs, the resource managers, and the application server.
The Java Transaction Service (JTS) [19] API is a Java binding of the CORBA Object Transaction Service (OTS) 1.1 specification. JTS provides transaction interoperability using the standard IIOP protocol for transaction propagation between servers. The JTS API is intended for vendors who implement transaction processing infrastructure for enterprise middleware. For example, an Enterprise Beans server vendor may use a JTS implementation as the underlying transaction manager.
8.2. Sample Scenarios
This section describes several scenarios that illustrate the distributed transaction capabilities of the Enterprise Beans architecture.
8.2.1. Update of Multiple Databases
The Enterprise Beans architecture makes it possible for an application program to update data in multiple databases in a single transaction.
In the following figure, a client invokes the enterprise bean X. Bean X updates data using two database connections that the Deployer configured to connect with two different databases, A and B. Then X calls another enterprise bean, Y. Bean Y updates data in database C. The Enterprise Beans server ensures that the updates to databases A, B, and C are either all committed or all rolled back.
The application programmer does not have to do anything to ensure transactional semantics. Behind the scenes, the Enterprise Beans server enlists the database connections as part of the transaction. When the transaction commits, the Enterprise Beans server and the database systems perform a two-phase commit protocol to ensure atomic updates across all three databases.
8.2.2. Messages Sent or Received Over Jakarta Messaging Sessions and Update of Multiple Databases
The Enterprise Beans architecture makes it possible for an application program to send messages to or receive messages from one or more Jakarta Messaging Destinations and/or to update data in one or more databases in a single transaction.
In the following figure, a client invokes the enterprise bean X. Bean X sends a message to a Jakarta Messaging queue A and updates data in a database B using connections that the Deployer configured to connect with a Jakarta Messaging provider and a database. Then X calls another enterprise bean, Y. Bean Y updates data in database C. The Enterprise Beans server ensures that the operations on A, B, and C are either all committed, or all rolled back.
The application programmer does not have to do anything to ensure transactional semantics. The enterprise beans X and Y perform the message send and database updates using the standard Jakarta Messaging and JDBC™ APIs. Behind the scenes, the Enterprise Beans server enlists the session on the connection to the Jakarta Messaging provider and the database connections as part of the transaction. When the transaction commits, the Enterprise Beans server and the messaging and database systems perform a two-phase commit protocol to ensure atomic updates across all the three resources.
In the following figure, a client sends a message to the Jakarta Messaging queue A serviced by the message-driven bean X. Bean X updates data using two database connections that the Deployer configured to connect with two different databases, B and C. The Enterprise Beans server ensures that the dequeuing of the Jakarta Messaging message, its receipt by bean X, and the updates to databases B and C are either all committed or all rolled back.
8.2.3. Update of Databases via Multiple Enterprise Beans Servers
The Enterprise Beans architecture allows updates of data at multiple sites to be performed in a single transaction.
In the following figure, a client invokes the enterprise bean X. Bean X updates data in database A, and then calls another enterprise bean Y that is installed in a remote Enterprise Beans server. Bean Y updates data in database B. The Enterprise Beans architecture makes it possible to perform the updates to databases A and B in a single transaction.
When X invokes Y, the two Enterprise Beans servers cooperate to propagate the transaction context from X to Y. This transaction context propagation is transparent to the application-level code.
At transaction commit time, the two Enterprise Beans servers use a distributed two-phase commit protocol (if the capability exists) to ensure the atomicity of the database updates.
8.2.4. Client-Managed Demarcation
A Java client can use the
jakarta.transaction.UserTransaction
interface
to explicitly demarcate transaction boundaries. The client program
obtains the jakarta.transaction.UserTransaction
interface through
dependency injection or lookup in the bean’s EJBContext or in the JNDI
name space.
A client program using explicit transaction demarcation may perform, via enterprise beans, atomic updates across multiple databases residing at multiple Enterprise Beans servers, as illustrated in the following figure.
The application programmer demarcates the transaction with begin and commit calls. If the enterprise beans X and Y are configured to use a client transaction (i.e., their methods have transaction attributes that either require or support an existing transaction context), the Enterprise Beans server ensures that the updates to databases A and B are made as part of the client’s transaction.
8.2.5. Container-Managed Demarcation
Whenever a client invokes a method on an enterprise bean’s business interface, on the bean no-interface view, on a home or component interface, or a message listener method, the container interposes on the method invocation. The interposition allows the container to control transaction demarcation declaratively through the transaction attribute set by the developer. (See Specification of the Transaction Attributes for a Bean’s Methods for a description of transaction attributes.)
For example, if a session bean method is
configured with the REQUIRED
transaction attribute, the container
behaves as follows: If the client request is not associated with a
transaction context, the container automatically initiates a transaction
whenever a client invokes an enterprise bean method that requires a
transaction context. If the client request contains a
transaction context, the container includes
the enterprise bean method in the client transaction.
The following figure illustrates such a
scenario. A non-transactional client invokes the enterprise bean X, and
the invoked method has the REQUIRED
[42] transaction
attribute. Because the invocation from the client does not include a
transaction context, the container starts a new transaction before
dispatching the method on X. Bean X’s work is performed in the context
of the transaction. When X calls other enterprise beans (Y in our
example), the work performed by the other enterprise beans is also
automatically included in the transaction (subject to the transaction
attribute of the other enterprise bean).
The container automatically commits the transaction at the time X returns a reply to the client.
If a message-driven bean’s message
listener method is configured with the REQUIRED
transaction attribute,
the container automatically starts a new transaction before the delivery
of the message and, hence, before the invocation of the
method.[43]
The container automatically enlists the resource manager associated with the arriving message and all the resource managers accessed by the message listener method with the transaction.
8.3. Bean Provider’s Responsibilities
This section describes the Bean Provider’s view of transactions and defines the Bean Provider’s responsibilities.
8.3.1. Bean-Managed Versus Container-Managed Transaction Demarcation
When designing an enterprise bean, the developer must decide whether the enterprise bean will demarcate transactions programmatically in the business methods (bean-managed transaction demarcation), or whether the transaction demarcation is to be performed by the container based on the transaction attributes specified in metadata annotations or in the deployment descriptor (container-managed transaction demarcation). Typically enterprise beans will be specified to have container-managed transaction demarcation. This is the default if no transaction management type is specified.
A session bean or a message-driven bean can be designed with bean-managed transaction demarcation or with container-managed transaction demarcation. (But it cannot be both at the same time.)
An enterprise bean instance can access resource managers in a transaction only in the enterprise bean’s methods in which there is a transaction context available.
8.3.1.1. Non-Transactional Execution
Some enterprise beans may need to access resource managers that do not support an external transaction coordinator. The container cannot manage the transactions for such enterprise beans in the same way that it can for the enterprise beans that access resource managers that support an external transaction coordinator.
If an enterprise bean needs to access a
resource manager that does not support an external transaction
coordinator, the Bean Provider should design the enterprise bean with
container-managed transaction demarcation and assign the NOT_SUPPORTED
transaction attribute to the bean class or to all the bean’s methods.
The Enterprise Beans architecture does not specify the transactional semantics of the
enterprise bean methods. See Handling of Methods that Run with "an unspecified transaction context"
for how the container implements this case.
8.3.2. Isolation Levels
Transactions not only make completion of a unit of work atomic, but they also isolate the units of work from each other, provided that the system allows concurrent execution of multiple units of work.
The isolation level
describes the degree to which the access to a resource manager by
a transaction is isolated from the access to the resource manager by
other concurrently executing transactions.
The following are guidelines for managing isolation levels in enterprise beans.
-
The API for managing an isolation level is resource-manager-specific. (Therefore, the Enterprise Beans architecture does not define an API for managing isolation levels.)
-
If an enterprise bean uses multiple resource managers, the Bean Provider may specify the same or different isolation level for each resource manager. This means, for example, that if an enterprise bean accesses multiple resource managers in a transaction, access to each resource manager may be associated with a different isolation level.
-
The Bean Provider must take care when setting an isolation level. Most resource managers require that all accesses to the resource manager within a transaction are done with the same isolation level. An attempt to change the isolation level in the middle of a transaction may cause undesirable behavior, such as an implicit sync point (a commit of the changes done so far).
-
For session beans and message-driven beans with bean-managed transaction demarcation, the Bean Provider can specify the desirable isolation level programmatically in the enterprise bean’s methods, using the resource-manager specific API. For example, the Bean Provider can use the
java.sql.Connection.setTransactionIsolation
method to set the appropriate isolation level for database access. -
Additional care must be taken if multiple enterprise beans access the same resource manager in the same transaction. Conflicts in the requested isolation levels must be avoided.
8.3.3. Enterprise Beans Using Bean-Managed Transaction Demarcation
This subsection describes the requirements for the Bean Provider of an enterprise bean with bean-managed transaction demarcation.
The enterprise bean with bean-managed transaction demarcation must be a session bean or a message-driven bean.
An instance that starts a transaction must complete the transaction before it starts a new transaction.
The Bean Provider uses the
UserTransaction
interface to demarcate transactions. All updates to the
resource managers between
the UserTransaction.begin
and UserTransaction.commit
methods are performed in a transaction. While an instance is in
a transaction, the instance must not attempt to use the resource-manager
specific transaction demarcation API (e.g. it must not invoke the commit
or rollback method on the java.sql.Connection interface or on the
jakarta.jms.Session
interface).[45]
A stateful session bean instance may, but is
not required to, commit a started transaction before a business method
returns. If a transaction has not been completed by the end of a
business method, the container retains the association between the
transaction and the instance across multiple client calls until the
instance eventually completes the transaction. A stateful session bean
instance must commit a transaction before PostConstruct
, PreDestroy
,
PrePassivate
or PostActivate
lifecycle callback interceptor method
returns.
A stateless session bean instance must commit a transaction before a business method or timeout callback method returns.
A singleton session bean instance must commit
a transaction before a business method or timeout callback method or
PostConstruct
or PreDestroy
lifecycle callback interceptor method
returns.
A message-driven bean instance must commit a transaction before a message listener method or timeout callback method returns.
If AroundInvoke
interceptor methods are
applied to the business method or AroundTimeout
interceptor methods are
applied to the timeout callback method of a singleton or a stateless
session bean or a message-driven bean, the transaction must be completed
before the last AroundInvoke
or AroundTimeout
interceptor method
completes.
The following code segments illustrate a business method that performs a transaction involving two database connections.
@Stateless
@TransactionManagement(BEAN)
public class MySessionBean implements MySession {
@Resource
jakarta.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
@Resource
javax.sql.DataSource database2;
public void someMethod(...) {
java.sql.Connection con1;
java.sql.Connection con2;
java.sql.Statement stmt1;
java.sql.Statement stmt2;
try {
// obtain con1 object and set it up for transactions
con1 = database1.getConnection();
stmt1 = con1.createStatement();
// obtain con2 object and set it up for transactions
con2 = database2.getConnection();
stmt2 = con2.createStatement();
// Now do a transaction that involves con1 and con2.
// start the transaction
ut.begin();
// Do some updates to both con1 and con2. The container
// automatically enlists con1 and con2 with the
// transaction.
stmt1.executeQuery(...);
stmt1.executeUpdate(...);
stmt2.executeQuery(...);
stmt2.executeUpdate(...);
stmt1.executeUpdate(...);
stmt2.executeUpdate(...);
// commit the transaction
ut.commit();
} catch (...) {
// handle exceptions
...
} finally {
// release connections
con1.close();
con2.close();
...
}
}
...
}
The following code segments illustrate a business method that performs a transaction involving both a database connection and a Jakarta Messaging connection.
@Stateless
@TransactionManagement(BEAN)
public class MySessionBean implements MySession {
@Resource
jakarta.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
@Resource
jakarta.jms.QueueConnectionFactory qcf1;
@Resource
jakarta.jms.Queue queue1;
public void someMethod(...) {
java.sql.Connection dcon;
java.sql.Statement stmt;
jakarta.jms.QueueConnection qcon;
jakarta.jms.QueueSession qsession;
jakarta.jms.QueueSender qsender;
jakarta.jms.Message message;
try {
// obtain db conn object and set it up for transactions
dcon = database1.getConnection();
stmt = dcon.createStatement();
// obtain jms conn object and set up session for
// transactions
qcon = qcf1.createQueueConnection();
qsession = qcon.createQueueSession(true,0);
qsender = qsession.createSender(queue1);
message = qsession.createTextMessage();
message.setText("some message");
// Now do a transaction that involves both connections
// start the transaction
ut.begin();
// Do database updates and send message. The container
// automatically enlists dcon and qsession with the
// transaction.
stmt.executeQuery(...);
stmt.executeUpdate(...);
stmt.executeUpdate(...);
qsender.send(message);
// commit the transaction
ut.commit();
} catch (...) {
// handle exception s
...
} finally {
// release connections
dcon.close();
qcon.close();
...
}
}
...
}
The following code segments illustrate
a stateful session bean that retains a transaction across three client
calls, invoked in the following order: method1
, method2
, and
method3
.[46]
@Stateful
@TransactionManagement(BEAN)
public class MySessionBean implements MySession {
@Resource
jakarta.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
@Resource
javax.sql.DataSource database2;
java.sql.Connection con1;
java.sql.Connection con2;
public void method1(...) {
java.sql.Statement stmt;
// start a transaction
ut.begin();
// make some updates on con1
con1 = database1.getConnection();
stmt = con1.createStatement();
stmt.executeUpdate(...);
stmt.executeUpdate(...);
// The container retains the transaction associated with the
// instance to the next client call (which is method2(...)).
}
public void method2(...) {
java.sql.Statement stmt;
con2 = database2.getConnection();
stmt = con2.createStatement();
stmt.executeUpdate(...);
stmt.executeUpdate(...);
// The container retains the transaction associated with the
// instance to the next client call (which is method3(...)).
}
public void method3(...) {
java.sql.Statement stmt;
// make some more updates on con1 and con2
stmt = con1.createStatement();
stmt.executeUpdate(...);
stmt = con2.createStatement();
stmt.executeUpdate(...);
try {
// commit the transaction
ut.commit();
} finally {
// release connections
con1.close();
con2.close();
...
}
}
...
}
It is possible for an enterprise bean to open
and close a database connection in each business method (rather than
hold the connection open until the end of transaction). The following
code segments illustrate a stateful session bean for which the client
executes the sequence of methods (method1
, method2
, method2
,
method2
, and method3
). In this scenario, all the database updates
done by the multiple invocations of method2
are performed in the scope
of the same transaction, which is the transaction started in method1
and committed in method3
.
@Stateful
@TransactionManagement(BEAN)
public class MySessionBean implements MySession {
@Resource
jakarta.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
public void method1(...) {
// start a transaction
ut.begin();
}
public void method2(...) {
java.sql.Connection con;
java.sql.Statement stmt;
try {
// open connection
con = database1.getConnection();
// make some updates on con
stmt = con.createStatement();
stmt.executeUpdate(...);
stmt.executeUpdate(...);
} finally {
// close the connection
con.close();
...
}
}
public void method3(...) {
// commit the transaction
ut.commit();
}
...
}
8.3.3.1. getRollbackOnly and setRollbackOnly Methods
An enterprise bean with
bean-managed transaction demarcation must
not use the getRollbackOnly
and setRollbackOnly
methods of the
EJBContext
interface.
An enterprise bean with bean-managed transaction demarcation has no need to use these methods, because of the following reasons:
-
An enterprise bean with bean-managed transaction demarcation can obtain the status of a transaction by using the
getStatus
method of thejakarta.transaction.UserTransaction
interface. -
An enterprise bean with bean-managed transaction demarcation can rollback a transaction using the
rollback
method of thejakarta.transaction.UserTransaction
interface.
8.3.4. Enterprise Beans Using Container-Managed Transaction Demarcation
This subsection describes the requirements for the Bean Provider of an enterprise bean using container-managed transaction demarcation.
The enterprise
bean’s business methods, message listener methods, business method
interceptor methods, lifecycle callback interceptor methods, or timeout
callback methods must not use any resource-manager specific transaction
management methods that would interfere with the container’s demarcation
of transaction boundaries. For example, the enterprise bean methods must
not use the following methods of the java.sql.Connection
interface:
commit
, setAutoCommit
, and rollback
; or the following methods of the
jakarta.jms.Session
interface: commit
and rollback
.
The enterprise bean’s business methods,
message listener methods, business method
interceptor methods, lifecycle callback interceptor methods, or timeout
callback methods must not attempt to obtain or use the
jakarta.transaction.UserTransaction
interface.
The following code segments illustrate a business method in an enterprise bean with container-managed transaction demarcation. The business method updates two databases using JDBC™ connections. The container provides transaction demarcation as specified by the transaction attribute.[47]
@Stateless
public class MySessionBean implements MySession {
...
@TransactionAttribute(REQUIRED)
public void someMethod(...) {
java.sql.Connection con1;
java.sql.Connection con2;
java.sql.Statement stmt1;
java.sql.Statement stmt2;
try {
// obtain con1 and con2 connection objects
con1 = ...;
con2 = ...;
stmt1 = con1.createStatement();
stmt2 = con2.createStatement();
// Perform some updates on con1 and con2. The container
// automatically enlists con1 and con2 with the
// container-managed transaction.
stmt1.executeQuery(...);
stmt1.executeUpdate(...);
stmt2.executeQuery(...);
stmt2.executeUpdate(...);
stmt1.executeUpdate(...);
stmt2.executeUpdate(...);
} finally {
// release connections
con1.close();
con2.close();
...
}
}
...
}
8.3.4.1. jakarta.ejb.SessionSynchronization Interface
A stateful
session bean with container-managed transaction demarcation can
optionally implement the jakarta.ejb.SessionSynchronization
interface or
use the session synchronization annotations. Their use is described in
The Session Synchronization Notifications for Stateful Session Beans.
8.3.4.2. jakarta.ejb.EJBContext.setRollbackOnly Method
An enterprise
bean with container-managed transaction demarcation can use the
setRollbackOnly
method of its EJBContext
object to mark the transaction
such that the transaction can never commit. Typically, an enterprise
bean marks a transaction for rollback to protect data integrity before
throwing an application exception, if the application exception class
has not been specified to automatically cause the container to rollback
the transaction.
For example, an AccountTransfer
bean which
debits one account and credits another account could mark a transaction
for rollback if it successfully performs the debit operation, but
encounters a failure during the credit operation.
8.3.4.3. jakarta.ejb.EJBContext.getRollbackOnly method
An enterprise
bean with container-managed transaction demarcation can use the
getRollbackOnly
method of its EJBContext
object to test if the current
transaction has been marked for rollback. The transaction might have
been marked for rollback by the enterprise bean itself, by other
enterprise beans, or by other components (outside of the Enterprise Beans
specification scope) of the transaction processing infrastructure.
8.3.5. Use of Jakarta Messaging APIs in Transactions
The Bean Provider should not make use of the Jakarta Messaging request/reply paradigm (sending of a Jakarta Messaging message, followed by the synchronous receipt of a reply to that message) within a single transaction. Because a Jakarta Messaging message is typically not delivered to its final destination until the transaction commits, the receipt of the reply within the same transaction will not take place.
Because the container manages the
transactional enlistment of Jakarta Messaging sessions on behalf of a bean, the
parameters of the createSession(boolean transacted, int acknowledgeMode)
,
createQueueSession(boolean transacted, int acknowledgeMode)
and
createTopicSession(boolean transacted, int acknowledgeMode)
methods are ignored. It is recommended that the Bean
Provider specify that a session is transacted, but provide 0
for the
value of the acknowledgment mode.
The Bean Provider should not use the Jakarta Messaging
acknowledge
method either within a transaction or within an
unspecified transaction context. Message acknowledgment in an
unspecified transaction context is handled by the container.
Handling of Methods that Run with "an unspecified transaction context" describes some of the techniques that
the container can use for the implementation of a method invocation with
an unspecified transaction context.
8.3.6. Specification of a Bean’s Transaction Management Type
By default, a session bean or message-driven
bean has container managed transaction demarcation if the transaction
management type is not specified. The Bean Provider of a session bean or
a message-driven bean can use the TransactionManagement
annotation to
declare whether the session bean or message-driven bean uses
bean-managed or container-managed transaction demarcation. The value of
the TransactionManagement
annotation is either CONTAINER
or BEAN
.
The TransactionManagement
annotation is applied to the enterprise bean
class.
Alternatively, the Bean Provider can use the
transaction-type
deployment descriptor element to specify the bean’s
transaction management type. If the deployment descriptor is used, it is
only necessary to explicitly specify the bean’s transaction management
type if bean-managed transaction is used.
The transaction management type of a bean is determined by the Bean Provider. The Application Assembler is not permitted to use the deployment descriptor to override a bean’s transaction management type regardless of whether it has been explicitly specified or defaulted by the Bean Provider. (See Deployment Descriptor for information about the deployment descriptor.)
8.3.7. Specification of the Transaction Attributes for a Bean’s Methods
The Bean Provider
of an enterprise bean with container-managed transaction demarcation may
specify the transaction attributes for the enterprise bean’s methods. By
default, the value of the transaction attribute for a method of a bean
with container-managed transaction demarcation is the REQUIRED
transaction attribute, and the transaction attribute does not need to be
explicitly specified in this case.
A transaction attribute is a value associated with each of the following methods
-
a method of a bean’s business interface
-
a method exposed through the bean class no-interface view
-
a message listener method of a message-driven bean
-
a timeout callback method
-
a stateless or singleton session bean’s web service endpoint method
-
for beans written to the Enterprise Beans 2.1 and earlier client view, a method of a session bean’s home or component interface
-
a
PostConstruct
orPreDestroy
lifecycle callback interceptor method of a singleton session bean -
a
PostConstruct
,PreDestroy
,PrePassivate
orPostActivate
lifecycle callback interceptor method of a stateful session bean
The transaction attribute specifies how the container must manage transactions for a method when a client invokes the method.
Transaction attributes are specified for the following methods:
-
For a session bean written to the Enterprise Beans 3.x client view API, the transaction attributes are specified for those methods of the session bean class that correspond to the bean’s business interface, the direct and indirect superinterfaces of the business interface, methods exposed through the bean class no-interface view, and for the timeout callback methods, if any.
-
For a stateless session bean or singleton session bean that provides a web service client view, the transaction attributes are specified for the bean’s web service endpoint methods, and for the timeout callback methods, if any.
-
For a singleton session bean, the transaction attributes are specified for the
PostConstruct
andPreDestroy
lifecycle callback interceptor methods, if any. In order to specify the transaction attribute for aPostConstuct
orPreDestroy
method of a singleton session bean, the transaction attribute must be specified for the method(s) on the bean class, rather than for a superclass orPostConstruct
orPreDestroy
interceptor method. -
For a stateful session bean, the transaction attributes are specified for the
PostConstruct
,PreDestroy
,PrePassivate
orPostActivate
lifecycle callback interceptor methods, if any. In order to specify the transaction attribute for aPostConstruct
,PreDestroy
,PrePassivate
orPostActivate
method of a stateful session bean, the transaction attribute must be specified for the method(s) on the bean class, rather than for a superclass orPostConstruct
,PreDestroy
,PrePassivate
orPostActivate
interceptor method. -
For a message-driven bean, the transaction attributes are specified for the message listenermethods on the message-driven bean class and for the timeout callback methods, if any.
-
For a session bean written to the Enterprise Beans 2.1 and earlier client view, the transaction attributes are specified for the methods of the component interface and all the direct and indirect superinterfaces of the component interface, excluding the methods of the
jakarta.ejb.EJBObject
orjakarta.ejb.EJBLocalObject
interface; and for the timeout callback methods, if any. Transaction attributes must not be specified for the methods of a session bean’s home interface.
By default, if a TransactionAttribute
annotation is not specified for a method of an enterprise bean with
container-managed transaction demarcation, the value of the transaction
attribute for the method is defined to be REQUIRED
. The rules for the
specification of transaction attributes are defined in Specification of Transaction Attributes with Metadata Annotations.
The Bean Provider may use the deployment
descriptor as an alternative to metadata annotations to specify the
transaction attributes or as a means to supplement or override metadata
annotations for transaction attributes. If a transaction attribute value
is not specified in the deployment descriptor, it is assumed that the
transaction attribute specified in annotations applies, or—in the case
that no annotation has been specified—that the value is Required
.
The Application Assembler is permitted to override the transaction attribute values using the bean’s deployment descriptor. The Deployer is also permitted to override the transaction attribute values at deployment time. Caution should be exercised when overriding the transaction attributes of an application, as the transactional structure of an application is typically intrinsic to the semantics of the application.
Enterprise
Beans defines the following values for the TransactionAttribute
metadata annotation:
-
MANDATORY
-
REQUIRED
-
REQUIRES_NEW
-
SUPPORTS
-
NOT_SUPPORTED
-
NEVER
The deployment descriptor values that correspond to these annotation values are the following:
-
Mandatory
-
Required
-
RequiresNew
-
Supports
-
NotSupported
-
Never
In this chapter, we use the
TransactionAttribute
annotation values to refer to transaction
attributes. As noted, however, the deployment descriptor may be used.
Refer to Container-Managed Transaction Demarcation for Business Methods for the specification of how the value of the transaction attribute affects the transaction management performed by the container.
For a message-driven bean’s message listener
methods (or interface), only the REQUIRED
and NOT_SUPPORTED
transaction attributes may be used.
For an enterprise bean’s timeout callback
methods, only the REQUIRED
, REQUIRES_NEW
and NOT_SUPPORTED
transaction attributes may be used.
For a session bean’s asynchronous business
methods, only the REQUIRED
, REQUIRES_NEW
, and NOT_SUPPORTED
transaction
attributes may be used.
For a singleton session bean’s PostConstruct
and PreDestroy
lifecycle callback interceptor methods, only the
REQUIRED
, REQUIRES_NEW
, and NOT_SUPPORTED
transaction attributes
may be used.
For a stateful session bean’s PostConstruct
,
PreDestroy
, PrePassivate
or PostActivate
lifecycle callback interceptor
methods, only the REQUIRES_NEW
and NOT_SUPPORTED
transaction
attributes may be used.
If an enterprise bean implements the
jakarta.ejb.SessionSynchronization
interface or uses any of the session
synchronization annotations, only the following values may be used for
the transaction attributes of the bean’s methods: REQUIRED
,
REQUIRES_NEW
, MANDATORY
.[48]
The above restriction is necessary to ensure that the enterprise bean is invoked only in a transaction. If the bean were invoked without a transaction, the container would not be able to send the transaction synchronization calls.
8.3.7.1. Specification of Transaction Attributes with Metadata Annotations
The following rules apply for the specification of transaction attributes using Java language metadata annotations.
The TransactionAttribute
annotation is used
to specify a transaction attribute. The value of the transaction
attribute annotation is given by the enum TransactionAttributeType
:
public enum TransactionAttributeType {
MANDATORY,
REQUIRED,
REQUIRES_NEW,
SUPPORTS,
NOT_SUPPORTED,
NEVER
}
The transaction attributes for the methods of a bean class may be specified on the class, the business methods of the class, or both.
Specifying the TransactionAttribute
annotation on the bean class means that it applies to all applicable
business interface methods of the class. If the transaction attribute
type is not specified, it is assumed to be REQUIRED
. The absence of a
transaction attribute specification on the bean class is equivalent to
the specification of TransactionAttribute(REQUIRED)
on the bean class.
A transaction attribute may be specified on a method of the bean class to override the transaction attribute value explicitly or implicitly specified on the bean class.
If the bean class has superclasses, the following additional rules apply.
-
A transaction attribute specified on a superclass S applies to the business methods defined by S. If a class-level transaction attribute is not specified on S, it is equivalent to specification of
TransactionAttribute(REQUIRED)
on S. -
A transaction attribute may be specified on a business method M defined by class S to override for method M the transaction attribute value explicitly or implicitly specified on the class S.
-
If a method M of class S overrides a business method defined by a superclass of S, the transaction attribute of M is determined by the above rules as applied to class S.
Example:
@TransactionAttribute(SUPPORTS)
public class SomeClass {
public void aMethod() {...}
public void bMethod() {...}
...
}
@Stateless
public class ABean extends SomeClass implements A {
public void aMethod() {...}
@TransactionAttribute(REQUIRES_NEW)
public void cMethod() {...}
...
}
Assuming aMethod
, bMethod
, cMethod
are methods of interface A
, their transaction attributes are
REQUIRED
, SUPPORTS
, and REQUIRES_NEW
respectively.
8.3.7.2. Specification of Transaction Attributes in the Deployment Descriptor
The following rules apply for the specification of transaction attributes in the deployment descriptor. (See Deployment Descriptor XML Schema for the complete syntax of the deployment descriptor.)
Note that even in the absence of the use of
annotations, it is not necessary to explicitly specify transaction
attributes for all of the methods listed in Specification of the Transaction Attributes for a Bean’s Methods.
If a transaction attribute is not
specified for a method in an Enterprise Beans deployment descriptor, the transaction
attribute defaults to Required
.
If the deployment descriptor is used to override annotations, and transaction attributes are not specified for some methods, the values specified in annotations (whether explicit or defaulted) will apply for those methods.
Use of the container-transaction element
The container-transaction
element may be used
to define the transaction attributes for the following methods:
-
business interface methods
-
home interface methods
-
component interface methods
-
message-listener interface methods
-
no-interface view methods
-
web service endpoint methods
-
singleton
PostConstruct
andPreDestroy
methods -
stateful session bean
PostConstruct
,PreDestroy
,PrePassivate
orPostActivate
methods (see limitations) -
timeout callback methods
Each container-transaction
element consists
of a list of one or more method elements, and the trans-attribute
element. The container-transaction
element specifies that all the listed
methods are assigned the specified transaction attribute value. It is
required that all the methods specified in a single
container-transaction
element be methods of the same enterprise bean.
The method
element uses the ejb-name
, method-intf
, method-name
, and method-params
elements to denote one or more methods.
The optional method-intf
element can be
used to differentiate between methods with the same name and signature
that are multiply defined across the business, component, and home
interfaces, web service endpoint, no-interface view, singleton and
stateful session bean lifecycle callbacks, and/or timeout callbacks.
However, if the same method is a method of a local business interface,
local component interface, or no-interface view, the same transaction
attribute applies to the method for all of them. Likewise, if the same
method is a method of both a remote business interface and the remote
component interface, the same transaction attribute applies to the
method for both interfaces.
There are three legal styles of composing the
method
element:
Style 1:
<method>
<ejb-name>EJBNAME</ejb-name>
<method-name>*</method-name>
</method>
This style is used to specify a default value of the transaction attribute for the following methods, if any, of the specified enterprise bean for which there is no Style 2 or Style 3 element specified:
-
All methods of the business, home, or component interface
-
All no-interface view methods
-
All message listener methods
-
Web service endpoint methods
-
Singleton
PostConstruct
andPreDestroy
methods -
All timeout callback methods
There must be at most one
container-transaction
element that uses the Style 1 method
element for a
given enterprise bean, unless the method-intf
element is used with this
style.
This style may be used for stateful session
bean lifecycle callback methods to specify their transaction attributes
if used with the method-intf
element value LifecycleCallback
.
Style 2:
<method>
<ejb-name>EJBNAME</ejb-name>
<method-name>METHOD</method-name>
</method>
This style is used for referring to a specified method of a business,
home, or component interface method; no-interface view method; message
listener method; web service endpoint method; singleton PostConstruct
and PreDestroy
methods; or timeout callback method of the specified
enterprise bean. If there are multiple methods with the same overloaded
name, this style refers to all the methods with the same name.
There must be at most one
container-transaction element that uses the Style 2 method
element for a
given method name, unless the method-intf
element is used with this
style. If there is also a container-transaction element that uses Style
1 element for the same bean, the value specified by the Style 2 element
takes precedence.
This style may be used to refer to stateful
session bean PostConstruct
, PreDestroy
, PrePassivate
or PostActivate
methods to specify their transaction attributes if any of the following
is true:
-
There is only one method with this name in the specified enterprise bean
-
All overloaded methods with this name in the specified enterprise bean are lifecycle callback methods
-
The
method-intf
element is specified and it containsLifecycleCallback
as the value
Style 3:
<method>
<ejb-name>EJBNAME</ejb-name>
<method-name>METHOD</method-name>
<method-params>
<method-param>PARAMETER_1</method-param>
...
<method-param>PARAMETER_N</method-param>
</method-params>
</method>
This style is used to refer to a single method within a set of methods
with an overloaded name. If there is also a container-transaction
element that uses the Style 2 element for the method name, or the Style
1 element for the bean, the value specified by the Style 3 element takes
precedence.
The following is an example of the
specification of the transaction attributes in the deployment
descriptor. The updatePhoneNumber
method of the EmployeeRecord
enterprise bean is assigned the transaction attribute Mandatory
; all
other methods of the EmployeeRecord
bean are assigned the attribute
Required
. All the methods of the enterprise bean AardvarkPayroll
are
assigned the attribute RequiresNew
.
<ejb-jar>
...
<assembly-descriptor>
...
<container-transaction>
<method>
<ejb-name>EmployeeRecord</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>EmployeeRecord</ejb-name>
<method-name>updatePhoneNumber</method-name>
</method>
<trans-attribute>Mandatory</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>RequiresNew</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
8.4. Application Assembler’s Responsibilities
This section describes the view and responsibilities of the Application Assembler.
There is no mechanism for an Application Assembler to affect enterprise beans with bean-managed transaction demarcation. The Application Assembler must not define transaction attributes for an enterprise bean with bean-managed transaction demarcation.
The Application Assembler can use the deployment descriptor transaction attribute mechanism described above to override or change the transaction attributes for enterprise beans using container-managed transaction demarcation.
8.5. Deployer’s Responsibilities
The Deployer is permitted to override or change the values of transaction attributes at deployment time.
Compatibility Note: For applications written to the Enterprise Beans 2.1 specification (and earlier), the Deployer is responsible for ensuring that the methods of the deployed enterprise beans with container-managed transaction demarcation have been assigned a transaction attribute if this has not be specified in the deployment descriptor.
8.6. Container Provider Responsibilities
This section defines the responsibilities of the Container Provider.
Every client method invocation on a session bean via the bean’s business interface (and/or home and component interface), no-interface view, web service endpoint, and every invocation of a message listener method on a message-driven bean is interposed by the container, and every connection to a resource manager used by an enterprise bean is obtained via the container. This managed execution environment allows the container to affect the enterprise bean’s transaction management.
This does not imply that the container must
interpose on every resource manager access performed by the enterprise
bean. Typically, the container interposes only on the resource manager
connection factory (e.g. a JDBC data source) JNDI look up by registering
the container-specific implementation of the resource manager connection
factory object. The resource manager connection factory object allows
the container to obtain the javax.transaction.xa.XAResource
interface
as described in the Jakarta Transactions specification and pass it to the transaction
manager. After the set up is done, the enterprise bean communicates with
the resource manager without going through the container.
8.6.1. Bean-Managed Transaction Demarcation
This subsection defines the container’s responsibilities for the transaction management of enterprise beans with bean-managed transaction demarcation.
Bean-managed transaction demarcation can be used with session and message-driven beans.
The container must manage client invocations to an enterprise bean instance with bean-managed transaction demarcation as follows. When a client invokes a business method via one of the enterprise bean’s client views, the container suspends any transaction that may be associated with the client request. If there is a transaction associated with the instance (this would happen if a stateful session bean instance started the transaction in some previous business method), the container associates the method execution with this transaction. If there are interceptor methods associated with the bean instances, these actions are taken before the interceptor methods are invoked.
The container must make the
jakarta.transaction.UserTransaction
interface available to the enterprise
bean’s business method, message listener method, interceptor method, or
timeout callback method via dependency injection into the enterprise
bean class or interceptor class, through lookup via the
jakarta.ejb.EJBContext
interface, and in the JNDI naming context under
java:comp/UserTransaction
. When an instance uses the
jakarta.transaction.UserTransaction
interface to demarcate a transaction,
the container must enlist all the resource managers used by the instance
between the begin
and commit
—or rollback
—methods with the
transaction.[49]
When the instance attempts to commit
the transaction, the container is responsible for the global
coordination of the transaction commit.[50]
In the case of a stateful session bean, it is possible that the business method or interceptor method that started a transaction completes without committing or rolling back the transaction. In such a case, the container must retain the association between the transaction and the instance across multiple client calls until the instance commits or rolls back the transaction. When the client invokes the next business method, the container must invoke the business method (and any applicable interceptor methods for the bean) in this transaction context.
If a stateless or singleton session bean instance starts a transaction in a business method or interceptor method, it must commit the transaction before the business method (or all its interceptor methods) returns. The container must detect the case in which a transaction was started, but not completed, in the business method or interceptor method for the business method, and handle it as follows:
-
Log this as an application error to alert the System Administrator.
-
Roll back the started transaction.
-
If this a stateless session bean, discard the bean instance.[51]
-
Throw the
jakarta.ejb.EJBException
.[52] If the Enterprise Beans 2.1 client view is used, the container should throw thejava.rmi.RemoteException if the client is a remote client, and thejakarta.ejb.EJBException
if the client is a local client.
If a message-driven bean instance starts a transaction in a message listener method or interceptor method, it must commit the transaction before the message listener method (or all its interceptor methods) returns. The container must detect the case in which a transaction was started, but not completed, in a message listener method or interceptor method for the message listener method, and handle it as follows:
-
Log this as an application error to alert the System Administrator.
-
Roll back the started transaction.
-
Discard the instance of the message-driven bean.
If a session bean or message-driven bean instance starts a transaction in a timeout callback method, it must commit the transaction before the timeout callback method returns. The container must detect the case in which a transaction was started, but not completed, in a timeout callback method, and handle it as follows:
-
Log this as an application error to alert the System Administrator.
-
Roll back the started transaction.
-
If this is a stateless session bean or message-driven bean, discard the instance of the bean.
The actions performed by the container for an instance with bean-managed transaction are summarized by the following table. T1 is a transaction associated with a client request, T2 is a transaction that is currently associated with the instance (i.e. a transaction that was started but not completed by a previous business method).
Client’s transaction | Transaction currently associated with instance | Transaction associated with the method |
---|---|---|
none |
none |
none |
T1 |
none |
none |
none |
T2 |
T2 |
T1 |
T2 |
T2 |
The following items describe each entry in the table:
-
If the client request is not associated with a transaction and the instance is not associated with a transaction, or if the bean is a message-driven bean, the container invokes the instance with an unspecified transaction context.
-
If the client request is associated with a transaction T1, and the instance is not associated with a transaction, the container suspends the client’s transaction association and invokes the method with an unspecified transaction context. The container resumes the client’s transaction association (T1) when the method (together with any associated interceptor methods) completes. This case can never happen for a message-driven bean or for the invocation of a web service endpoint method of a session bean.
-
If the client request is not associated with a transaction and the instance is already associated with a transaction T2, the container invokes the instance with the transaction that is associated with the instance (T2). This case can never happen for a stateless session bean, singleton session bean, or a message-driven bean: it can only happen for a stateful session bean.
-
If the client is associated with a transaction T1, and the instance is already associated with a transaction T2, the container suspends the client’s transaction association and invokes the method with the transaction context that is associated with the instance (T2). The container resumes the client’s transaction association (T1) when the method (together with any associated interceptor methods) completes. This case can never happen for a stateless session bean, singleton session bean, or a message-driven bean: it can only happen for a stateful session bean.
The container must allow the enterprise bean instance to serially perform several transactions in a method.
When an instance attempts to start a
transaction using the begin
method of the
jakarta.transaction.UserTransaction
interface while the instance has not
committed the previous transaction, the container must throw the
jakarta.transaction.NotSupportedException
in the begin
method.
The container must throw the
java.lang.IllegalStateException
if an instance of a bean with
bean-managed transaction demarcation attempts to invoke the
setRollbackOnly
or getRollbackOnly
method of the jakarta.ejb.EJBContext
interface.
8.6.2. Container-Managed Transaction Demarcation for Session Beans
The container is responsible for providing the transaction demarcation for the session beans declared with container-managed transaction demarcation. For these enterprise beans, the container must demarcate transactions as specified by the transaction attribute values specified using metadata annotations in the bean class or specified in the deployment descriptor.
8.6.2.1. Session Synchronization Callbacks
If a session bean class implements the
jakarta.ejb.SessionSynchronization
interface or uses the session
synchronization annotations, the container must invoke the afterBegin
,
beforeCompletion
, and afterCompletion
callbacks on the instance as part
of the transaction commit protocol. If a stateful session bean’s
PostConstruct
, PreDestroy
, PrePassivate
or PostActivate
lifecycle
callback interceptor methods are invoked in the scope of a transaction,
session synchronization callbacks for such transactions are not called
on the bean instance.
The container
invokes the afterBegin
method on an instance before it invokes the first
business method in a transaction.
The container invokes the beforeCompletion
method to give the enterprise bean instance the last chance to cause the
transaction to rollback. The instance may cause the transaction to roll
back by invoking the EJBContext.setRollbackOnly
method.
The container invokes the
afterCompletion(boolean committed)
method after the completion of the
transaction commit protocol to notify the enterprise bean instance of
the transaction outcome.
8.6.3. Container-Managed Transaction Demarcation for Business Methods
The following subsections define the responsibilities of the container for managing the invocation of an enterprise bean business method when the method is invoked via the enterprise bean’s business interface (and/or home or component interface), no-interface view, or web service endpoint. The container’s responsibilities depend on the value of the transaction attribute.
8.6.3.1. NOT_SUPPORTED
The container
invokes an enterprise bean method whose transaction attribute is set to
the NOT_SUPPORTED
value with an unspecified transaction context.
If a client calls with a transaction context, the container suspends the association of the transaction context with the current thread before invoking the enterprise bean’s business method. The container resumes the suspended association when the business method has completed. The suspended transaction context of the client is not passed to the resource managers or other enterprise bean objects that are invoked from the business method.
If the business method invokes other enterprise beans, the container passes no transaction context with the invocation.
Refer to Handling of Methods that Run with "an unspecified transaction context" for more details of how the container can implement this case.
8.6.3.2. REQUIRED
The container
must invoke an enterprise bean method whose transaction attribute is set
to the REQUIRED
value with a valid transaction context.
If a client invokes the enterprise bean’s
method while the client is associated with a transaction context, the
container invokes the enterprise bean’s method in the client’s
transaction context, unless the method is an asynchronous method. The
client’s transaction context does not propagate with an asynchronous
method invocation. The semantics of the REQUIRED
transaction attribute
for an asynchronous method are the same as REQUIRES_NEW
.
If the client invokes the enterprise bean’s method while the client is not associated with a transaction context, the container automatically starts a new transaction before delegating a method call to the enterprise bean business method. The container automatically enlists all the resource managers accessed by the business method with the transaction. If the business method invokes other enterprise beans, the container passes the transaction context with the invocation. The container attempts to commit the transaction when the business method has completed. The container performs the commit protocol before the method result is sent to the client.
8.6.3.3. SUPPORTS
The container
invokes an enterprise bean method whose transaction attribute is set to
SUPPORTS
as follows.
-
If the client calls with a transaction context, the container performs the same steps as described in the
REQUIRED
case. -
If the client calls without a transaction context, the container performs the same steps as described in the
NOT_SUPPORTED
case.
The SUPPORTS
transaction attribute must be
used with caution. This is because of the different transactional
semantics provided by the two possible modes of execution. Only the
enterprise beans that will execute correctly in both modes should use
the SUPPORTS
transaction attribute.
8.6.3.4. REQUIRES_NEW
The container
must invoke an enterprise bean method whose transaction attribute is set
to REQUIRES_NEW
with a new transaction context.
If the client invokes the enterprise bean’s method while the client is not associated with a transaction context, the container automatically starts a new transaction before delegating a method call to the enterprise bean business method. The container automatically enlists all the resource managers accessed by the business method with the transaction. If the business method invokes other enterprise beans, the container passes the transaction context with the invocation. The container attempts to commit the transaction when the business method has completed. The container performs the commit protocol before the method result is sent to the client.
If a client calls with a transaction context, the container suspends the association of the transaction context with the current thread before starting the new transaction and invoking the business method. The container resumes the suspended transaction association after the business method and the new transaction have been completed.
8.6.3.5. MANDATORY
The container
must invoke an enterprise bean method whose transaction attribute is set
to MANDATORY
in a client’s transaction context. The client is required
to call with a transaction context.
-
If the client calls with a transaction context, the container performs the same steps as described in the
REQUIRED
case. -
If the client calls without a transaction context, the container throws the
jakarta.ejb.EJBTransactionRequiredException
.[53] If the Enterprise Beans 2.1 client view is used, the container throws thejakarta.transaction.TransactionRequiredException
exception if the client is a remote client, and thejakarta.ejb.TransactionRequiredLocalException
if the client is a local client.
8.6.3.6. NEVER
The container
invokes an enterprise bean method whose transaction attribute is set to
NEVER
without a transaction context defined by the Enterprise Beans specification.
The client is required to call without a transaction context.
-
If the client calls with a transaction context, the container throws the
jakarta.ejb.EJBException
.[54] If the Enterprise Beans 2.1 client view is used, the container throws the java.rmi.RemoteException exception if the client is a remote client, and thejakarta.ejb.EJBException
if the client is a local client. -
If the client calls without a transaction context, the container performs the same steps as described in the
NOT_SUPPORTED
case.
8.6.3.7. Transaction Attribute Summary
The following table provides a summary of the transaction context that the container passes to the business method and resource managers used by the business method, as a function of the transaction attribute and the client’s transaction context. T1 is a transaction passed with the client request, while T2 is a transaction initiated by the container.
Transaction attribute | Client’s transaction | Transaction associated with business method | Transaction associated with resource managers |
---|---|---|---|
NOT_SUPPORTED |
none |
none |
none |
T1 |
none |
none |
|
REQUIRED |
none |
T2 |
T2 |
T1 |
T1 Note A |
T1 |
|
SUPPORTS |
none |
none |
none |
T1 |
T1 |
T1 |
|
REQUIRES_NEW |
none |
T2 |
T2 |
T1 |
T2 |
T2 |
|
MANDATORY |
none |
error |
N/A |
T1 |
T1 |
T1 |
|
NEVER |
none |
none |
none |
T1 |
error |
N/A |
If the enterprise bean’s business method invokes other enterprise beans via their business interfaces or home and component interfaces, the transaction indicated in the column "Transaction associated with business method" will be passed as part of the client context to the target enterprise bean.
See Handling of Methods that Run with "an unspecified transaction context" for how the container handles the "none" case in Transaction Attribute Summary.
8.6.3.8. Handling of setRollbackOnly Method
The container
must handle the EJBContext.setRollbackOnly
method invoked from a
business method executing with the REQUIRED
, REQUIRES_NEW
, or MANDATORY
transaction attribute as follows:
-
The container must ensure that the transaction will never commit. Typically, the container instructs the transaction manager to mark the transaction for rollback.
-
If the container initiated the transaction immediately before dispatching the business method to the instance (as opposed to the transaction being inherited from the caller), the container must note that the instance has invoked the
setRollbackOnly
method. When the business method invocation completes, the container must roll back rather than commit the transaction. If the business method has returned normally or with an application exception, the container must pass the method result or the application exception to the client after the container performed the rollback. -
The container must throw the
java.lang.IllegalStateException
if theEJBContext.setRollbackOnly
method is invoked from a business method executing with theSUPPORTS
,NOT_SUPPORTED
, orNEVER
transaction attribute.
8.6.3.9. Handling of getRollbackOnly Method
The container
must handle the EJBContext.getRollbackOnly
method invoked from a
business method executing with the REQUIRED
, REQUIRES_NEW
, or
MANDATORY
transaction attribute.
The container must throw the
java.lang.IllegalStateException
if the EJBContext.getRollbackOnly
method
is invoked from a business method executing with the SUPPORTS
,
NOT_SUPPORTED
, or NEVER
transaction attribute.
8.6.4. Container-Managed Transaction Demarcation for Message-Driven Beans
The container is responsible for providing the transaction demarcation for the message-driven beans that the Bean Provider declared as with container-managed transaction demarcation. For these enterprise beans, the container must demarcate transactions as specified by annotations on the bean class or in the deployment descriptor. (See Deployment Descriptor for more information about the deployment descriptor.)
8.6.5. Container-Managed Transaction Demarcation for Message Listener Methods
The following subsections define the responsibilities of the container for managing the invocation of a message-driven bean’s message listener method. The container’s responsibilities depend on the value of the transaction attribute.
Only the NOT_SUPPORTED
and REQUIRED
transaction attributes may be used for message-driven bean message
listener methods. The use of the other transaction attributes is not
meaningful for message-driven bean message listener methods because
there is no pre-existing client transaction context (REQUIRES_NEW
,
SUPPORTS
) and no client to handle exceptions (MANDATORY
, NEVER
).
8.6.5.1. NOT_SUPPORTED
The container invokes a message-driven bean
message listener method whose transaction
attribute is set to NOT_SUPPORTED
with an unspecified transaction
context.
If the message listener method invokes other enterprise beans, the container passes no transaction context with the invocation.
8.6.5.2. REQUIRED
The container must invoke a message-driven
bean message listener method whose
transaction attribute is set to REQUIRED
with a valid transaction context. The resource managers accessed by the
message listener method within the transaction are enlisted with the
transaction. If the message listener method invokes other enterprise
beans, the container passes the transaction context with the invocation.
The container attempts to commit the transaction when the message
listener method has completed.
Messaging systems may differ in quality of service with regard to reliability and transactionality of the dequeuing of messages.
The requirement for Jakarta Messaging are as follows:
8.6.5.3. Handling of setRollbackOnly Method
The container must handle the
EJBContext.setRollbackOnly
method invoked
from a message listener method executing with the REQUIRED
transaction
attribute as follows:
-
The container must ensure that the transaction will never commit. Typically, the container instructs the transaction manager to mark the transaction for rollback.
-
The container must note that the instance has invoked the
setRollbackOnly
method. When the method invocation completes, the container must roll back rather than commit the transaction.
The container must throw and log the
java.lang.IllegalStateException
if the EJBContext.setRollbackOnly
method
is invoked from a message listener method executing with the
NotSupported
transaction attribute
8.6.5.4. Handling of getRollbackOnly Method
The container must handle the
EJBContext.getRollbackOnly()
method invoked
from a message listener method executing with the REQUIRED
transaction
attribute.
The container must throw and log the
java.lang.IllegalStateException
if the EJBContext.getRollbackOnly
method
is invoked from a message listener method executing with the
NOT_SUPPORTED
transaction attribute.
8.6.6. Local Transaction Optimization
The container may use a local transaction optimization for enterprise beans whose metadata annotations or deployment descriptor indicates that connections to a resource manager are shareable (see Declaration of Resource Manager Connection Factory References in Deployment Descriptor). The container manages the use of the local transaction optimization transparently to the application.
The container may use the optimization for
transactions initiated by the container for a bean with
container-managed transaction demarcation and for transactions initiated
by a bean with bean-managed transaction demarcation with the
UserTransaction
interface. The container cannot apply the optimization
for transactions imported from a different container.
8.6.7. Handling of Methods that Run with "an unspecified transaction context"
The term "an unspecified transaction context" is used in the Enterprise Beans specification to refer to the cases in which the Enterprise Beans architecture does not fully define the transaction semantics of an enterprise bean method execution.
This includes the following cases:
-
The execution of a method of an enterprise bean with container-managed transaction demarcation for which the value of the transaction attribute is
NOT_SUPPORTED
,NEVER
, orSUPPORTS
. -
The execution of a
PostConstruct
orPreDestroy
callback method of a stateless session bean with container-managed transaction demarcation.[55] -
The execution of a
PostConstruct
orPreDestroy
callback method of a message-driven bean with container-managed transaction demarcation.[56]
The Enterprise Beans specification does not prescribe how the container should manage the execution of a method with an unspecified transaction context—the transaction semantics are left to the container implementation. Some techniques for how the container may choose to implement the execution of a method with an unspecified transaction context are as follows (the list is not inclusive of all possible strategies):
-
The container may execute the method and access the underlying resource managers without a transaction context.
-
The container may treat each call of an instance to a resource manager as a single transaction (e.g. the container may set the auto-commit option on a JDBC connection).
-
The container may merge multiple calls of an instance to a resource manager into a single transaction.
-
The container may merge multiple calls of an instance to multiple resource managers into a single transaction.
-
If an instance invokes methods on other enterprise beans, and the invoked methods are also designated to run with an unspecified transaction context, the container may merge the resource manager calls from the multiple instances into a single transaction.
-
Any combination of the above.
Since the enterprise bean does not know which technique the container implements, the enterprise bean must be written conservatively not to rely on any particular container behavior.
A failure that occurs in the middle of the execution of a method that runs with an unspecified transaction context may leave the resource managers accessed from the method in an unpredictable state. The Enterprise Beans architecture does not define how the application should recover the resource managers’ state after such a failure.
8.7. Access from Multiple Clients in the Same Transaction Context
This section describes a more complex distributed transaction scenario, and specifies the container’s behavior required for this scenario.
8.7.1. Transaction "Diamond" Scenario with an Entity Object
An entity object [57] may be accessed by multiple clients in the same transaction. For example, program A may start a transaction, call program B and program C in the transaction context, and then commit the transaction. If programs B and C access the same entity object, the topology of the transaction creates a diamond.
An example (not realistic in practice) is a client program that tries to perform two purchases at two different stores within the same transaction. At each store, the program that is processing the client’s purchase request debits the client’s bank account.
It is difficult to implement an Enterprise Beans server that handles the case in which programs B and C access an entity object through different network paths. This case is challenging because many Enterprise Beans servers implement the Enterprise Beans container as a collection of multiple processes, running on the same or multiple machines. Each client is typically connected to a single process. If clients B and C connect to different Enterprise Beans container processes, and both B and C need to access the same entity object in the same transaction, the issue is how the container can make it possible for B and C to see a consistent state of the entity object within the same transaction.[58]
The above example illustrates a simple diamond. We use the term diamond to refer to any distributed transaction scenario in which an entity object is accessed in the same transaction through multiple network paths.
Note that in the diamond scenario the clients B and C access the entity object serially. Concurrent access to an entity object in the same transaction context would be considered an application programming error, and it would be handled in a container-specific way.
Note that the issue of handling diamonds is not unique to the Enterprise Beans architecture. This issue exists in all distributed transaction processing systems.
The following subsections define the responsibilities of the Enterprise Beans Roles when handling distributed transaction topologies that may lead to a diamond involving an entity object.
8.7.2. Container Provider’s Responsibilities
This subsection specifies the Enterprise Beans container’s responsibilities with respect to the diamond case involving an entity object.[57]
The Enterprise Beans specification requires that the container provide support for local diamonds. In a local diamond, components A, B, C, and D are deployed in the same Enterprise Beans container.
The Enterprise Beans specification does not require an Enterprise Beans container to support distributed diamonds. In a distributed diamond, a target entity object is accessed from multiple clients in the same transaction through multiple network paths, and the clients (programs B and C) are not enterprise beans deployed in the same Enterprise Beans container as the target entity object.
If the Container Provider chooses not to
support distributed diamonds, and if the container can detect that a
client invocation would lead to a diamond, the container should throw
the jakarta.ejb.EJBException
(or java.rmi.RemoteException
if the Enterprise Beans 2.1
remote client view is used).
8.7.3. Bean Provider’s Responsibilities
This subsection specifies the Bean Provider’s responsibilities with respect to the diamond case involving an entity object.[57]
The diamond case is transparent to the Bean Provider—the Bean Provider does not have to code the enterprise bean differently for the bean to participate in a diamond. Any solution to the diamond problem implemented by the container is transparent to the bean and does not change the semantics of the bean.
8.7.4. Application Assembler and Deployer’s Responsibilities
This subsection specifies the Application Assembler and Deployer’s responsibilities with respect to the diamond case involving an entity object.[57]
The Application Assembler and Deployer should be aware that distributed diamonds might occur. In general, the Application Assembler should try to avoid creating unnecessary distributed diamonds.
If a distributed diamond is necessary, the Deployer should advise the container (using a container-specific API) that an entity objects of the entity bean may be involved in distributed diamond scenarios.
8.7.5. Transaction Diamonds involving Session Objects
While it is illegal for two clients to access the same session object, it is possible for applications that use session beans to encounter the diamond case. For example, program A starts a transaction and then invokes two different session objects.
If the session bean instances cache the same data item (e.g. the current balance of Account 100) across method invocations in the same transaction, most likely the program is going to produce incorrect results.
The problem may exist regardless of whether the two session objects are the same or different session beans. The problem may exist (and may be harder to discover) if there are intermediate objects between the transaction initiator and the session objects that cache the data.
There are no requirements for the Container Provider because it is impossible for the container to detect this problem.
The Bean Provider and Application Assembler must avoid creating applications that would result in inconsistent caching of data in the same transaction by multiple session objects.
9. Exception Handling
9.1. Overview and Concepts
9.1.1. Application Exceptions
An application exception is an exception defined by the Bean Provider as part of the business logic of an application. Application exceptions are distinguished from system exceptions in this specification.
Enterprise bean business methods use application exceptions to inform the client of abnormal application-level conditions, such as unacceptable values of the input arguments to a business method. A client can typically recover from an application exception. Application exceptions are not intended for reporting system-level problems.
For example, the Account
enterprise bean
may throw an application exception to report that a debit
operation
cannot be performed because of an insufficient balance. The Account
bean should not use an application exception to report, for example, the
failure to obtain a database connection.
An application exception may be defined in
the throws
clause of a method of an enterprise bean’s business
interface, no-interface view, home interface, component interface, or
web service endpoint, or of a message listener method.
An application exception class can either be
a subclass (direct or indirect) of
java.lang.Exception
(i.e., a "checked exception"), or a subclass of the
java.lang.RuntimeException
(an "unchecked exception").
An application exception may not be a subclass
of the java.rmi.RemoteException
. The java.rmi.RemoteException
and its
subclasses are reserved for system exceptions.
The
jakarta.ejb.CreateException
and jakarta.ejb.RemoveException
and subclasses
thereof are considered to be application exceptions. These exceptions
are used as standard application exceptions to report errors to the
client from the create and remove methods of the EJBHome and/or
EJBLocalHome interfaces of components written to the Enterprise Beans 2.1 client
view. These exceptions are covered by the rules on application
exceptions that are defined in this chapter.
9.1.2. Goals for Exception Handling
The Enterprise Beans specification for exception handling is designed to meet these high-level goals:
-
An application exception thrown by an enterprise bean instance should be reported to the client precisely (i.e., the client gets the same exception).[59]
-
An application exception thrown by an enterprise bean instance should not automatically cause a client’s transaction to be marked for rollback unless the application exception was defined to cause transaction rollback. The client should typically be given a chance to recover from an application exception.
-
An unexpected exception that may have left the instance’s state variables and/or underlying persistent data in an inconsistent state can be handled safely.
9.2. Bean Provider’s Responsibilities
This section describes the view and responsibilities of the Bean Provider with respect to exception handling.
9.2.1. Application Exceptions
The Bean Provider
defines application exceptions. Application exception that is a checked
exception is defined as such by being listed in the throws
clause of a
method on the bean’s business interface, no-interface view, home
interface, component interface, or web service endpoint. An application
exception that is an unchecked exception is defined as an application
exception by annotating it with the ApplicationException
metadata
annotation, or denoting it in the deployment descriptor with the
application-exception
element.
Because application exceptions are intended to be handled by the client, and not by the System Administrator, they should be used only for reporting business logic exceptions, not for reporting system level problems.
The Bean Provider is responsible for throwing the appropriate application exception from the business method to report a business logic exception to the client.
An application exception does not
automatically result in marking the transaction for rollback unless the
ApplicationException
annotation is applied to the exception class and
is specified with the rollback
element value true
or the
application-exception
deployment descriptor element for the exception
specifies the rollback
element as true
.[60] The
rollback
subelement of the application-exception
deployment
descriptor element may be explicitly specified to override the
rollback
value specified or defaulted by the ApplicationException
annotation.
The Bean Provider must do one of the following to ensure data integrity before throwing an application exception from an enterprise bean instance:
-
Ensure that the instance is in a state such that a client’s attempt to continue and/or commit the transaction does not result in loss of data integrity. For example, the instance throws an application exception indicating that the value of an input parameter was invalid before the instance performed any database updates.
-
If the application exception is not specified to cause transaction rollback, mark the transaction for rollback using the
EJBContext.setRollbackOnly
method before throwing the application exception. Marking the transaction for rollback will ensure that the transaction can never commit.
The Bean Provider is also responsible for
using the standard Enterprise Beans application exceptions
(jakarta.ejb.CreateException
, jakarta.ejb.RemoveException
,
jakarta.ejb.FinderException
, and subclasses thereof) for beans written to
the Enterprise Beans 2.1 and earlier client view as described in
Standard Application
Exceptions for Entities in Container-Managed Persistence and
Standard Application
Exceptions for Entities in Bean-Managed Persistence.
Bean Providers may define subclasses of the standard Enterprise Beans application exceptions and throw instances of the subclasses in the enterprise bean methods. A subclass will typically provide more information to the client that catches the exception.
By default, designating an unchecked
exception as an application exception also applies to subclasses of that
exception. This inheritance behavior can be disabled by setting the
inherited
element of the ApplicationException
annotation to false or by
setting the inherited
element of the application-exception
deployment
descriptor element to false
.
Example:
@ApplicationException(rollback=true)
public class ExceptionA extends RuntimeException { ... }
public class ExceptionB extends ExceptionA { ... }
@ApplicationException(inherited=false, rollback=false)
public class ExceptionC extends ExceptionB { ... }
public class ExceptionD extends ExceptionC { ... }
ExceptionA
is an application exception
that causes the transaction to be marked for rollback.
ExceptionB
is an application exception
that causes the transaction to be marked for rollback.
ExceptionC
is an application exception
that does not cause the transaction to be marked for rollback.
ExceptionD
is not an application exception.
9.2.2. System Exceptions
A system exception is an exception that is a
java.rmi.RemoteException
(or one of its subclasses) or a
RuntimeException
that is not an application exception.
This subsection describes how the Bean
Provider should handle various system-level exceptions and errors that
an enterprise bean instance may encounter during the execution of a
session bean business method, a message-driven bean message listener
method, an interceptor method, or a callback method (e.g. ejbLoad
).
An enterprise
bean business method, message listener method, business method
interceptor method, or lifecycle callback interceptor method may
encounter various exceptions or errors that prevent the method from
successfully completing. Typically, this happens because the exception
or error is unexpected, or the exception is expected but the Bean
Provider does not know how to recover from it. Examples of such
exceptions and errors are: failure to obtain a database connection, JNDI
exceptions, unexpected RemoteException
from invocation of other
enterprise beans,[61] unexpected RuntimeException
,
JVM errors, and so on.
If the enterprise bean method encounters a
system-level exception or error that does not allow the method to
successfully complete, the method should throw a suitable
non-application exception that is compatible with the method’s throws
clause. While the Enterprise Beans specification does not prescribe the exact usage
of the exception, it encourages the Bean Provider to follow these
guidelines:
-
If the bean method encounters a system exception or error, it should simply propagate the error from the bean method to the container (i.e., the bean method does not have to catch the exception).
-
If the bean method performs an operation that results in a checked exception [62] that the bean method cannot recover, the bean method should throw the
jakarta.ejb.EJBException
that wraps the original exception. -
Any other unexpected error conditions should be reported using the
jakarta.ejb.EJBException
.
Note that the jakarta.ejb.EJBException
is a
subclass of the java.lang.RuntimeException
, and therefore it does not
have to be listed in the throws
clauses of the business methods.
The container catches a non-application
exception; logs it (which can result in alerting the System
Administrator); and, unless the bean is a message-driven bean, throws
the jakarta.ejb.EJBException
[63] or, if the web
service client view is used, the java.rmi.RemoteException
. If the
Enterprise Beans 2.1 client view is used, the container throws the
java.rmi.RemoteException
(or subclass thereof) to the client if the
client is a remote client, or throws the jakarta.ejb.EJBException
(or
subclass thereof) to the client if the client is a local client. In the
case of a message-driven bean, the container logs the exception and then
throws a jakarta.ejb.EJBException
that wraps the original exception to
the resource adapter. (See [16]).
The exception that is seen by the client is described in Container Provider Responsibilities. It is determined both by the exception that is thrown by the container and/or bean and the client view.
The Bean Provider can rely on the container to perform the following tasks when catching a non-application exception:
-
The transaction in which the bean method participated will be rolled back.
-
Unless the bean is a singleton session bean, no other method will be invoked on an instance that threw a non-application exception.
This means that unless the bean is a singleton session bean, the Bean Provider does not have to perform any cleanup actions before throwing a non-application exception. It is the container that is responsible for the cleanup.
9.3. Container Provider Responsibilities
This section describes the responsibilities of the Container Provider for handling exceptions. The Enterprise Beans architecture specifies the container’s behavior for the following exceptions:
-
Exceptions from the business methods of session beans, including session bean business method interceptor methods.
-
Exceptions from message-driven bean message listener methods and business method interceptor methods.
-
Exceptions from timeout callback methods.
-
Exceptions from other container-invoked callbacks on the enterprise bean.
-
Exceptions from management of container-managed transaction demarcation.
9.3.1. Exceptions from a Session Bean’s Business Interface Methods and No-Interface View Methods
Handling of Exceptions Thrown by a Business Interface Method or No-interface View Method of a Bean with Container-Managed Transaction Demarcation specifies how the container must handle the exceptions thrown by the methods of the business interface and no-interface view for beans with container-managed transaction demarcation, including the exceptions thrown by business method interceptor methods. The table specifies the container’s action as a function of the condition under which the business method executes and the exception thrown by the method. The table also illustrates the exception that the client will receive and how the client can recover from the exception. (Client’s View of Exceptions describes the client’s view of exceptions in detail.) The notation "AppException" denotes an application exception.
Method condition | Method exception | Container’s action | Client’s view |
---|---|---|---|
Bean method runs in the context of the caller’s transaction
Note A. |
AppException |
Re-throw AppException. Mark the transaction for rollback if the application exception is specified as causing rollback. |
Receives AppException. Can attempt to continue computation in the transaction, and eventually
commit the transaction unless the application exception is specified as
causing rollback (the commit would also fail if the instance called
|
all other exceptions and errors |
Log the exception or error Note B. Mark the transaction for rollback. Discard instance Note C. Throw |
Receives Continuing transaction is fruitless. |
|
Bean method runs in the context of a transaction that the container
started immediately before dispatching the business method. |
AppException |
If the instance called If the application exception is specified as causing rollback, then rollback the transaction and then re-throw AppException. Otherwise, attempt to commit the transaction, and then re-throw AppException. |
Receives AppException. If the client executes in a transaction, the client’s transaction is not marked for rollback, and client can continue its work. |
all other exceptions |
Log the exception or error. Rollback the container-started transaction. Discard instance. Throw |
Receives If the client executes in a transaction, the client’s transaction may or may not be marked for rollback. |
|
Bean method runs with an unspecified transaction context. |
AppException |
Re-throw AppException. |
Receives AppException. If the client executes in a transaction, the client’s transaction is not marked for rollback, and client can continue its work. |
all other exceptions |
Log the exception or error. Discard instance. Throw |
Receives If the client executes in a transaction, the client’s transaction may or may not be marked for rollback. |
Notes:
[A] The caller can be
another enterprise bean or an arbitrary client program.
[B] Log the exception or error
means that the container logs the exception or error so that the
System Administrator is alerted of the problem.
[C] Discard instance
means that the container must not invoke any business methods or
container callbacks on the instance. Discarding does not apply if the
bean is a singleton session bean.
[D] If the business
interface is a remote business interface that extends java.rmi.Remote
,
the jakarta.transaction.TransactionRolledbackException
is thrown to the
client, which will receive this exception.
[E] If the business
interface is a remote business interface that extends java.rmi.Remote
,
the java.rmi.RemoteException
is thrown to the client, which will receive
this exception.
[F] If the business
interface is a remote business interface that extends java.rmi.Remote
,
the java.rmi.RemoteException
is thrown to the client, which will receive
this exception.
Handling of Exceptions Thrown by a Business Interface Method or No-Interface View Method of a Session Bean with Bean-Managed Transaction Demarcation specifies how the container must handle the exceptions thrown by the methods of the business interface or no-interface view for beans with bean-managed transaction demarcation, including the exceptions thrown by business method interceptor methods. The table specifies the container’s action as a function of the condition under which the business interface method executes and the exception thrown by the method. The table also illustrates the exception that the client will receive and how the client can recover from the exception. (Client’s View of Exceptions describes the client’s view of exceptions in detail.)
Bean method condition | Bean method exception | Container action | Client receives |
---|---|---|---|
Bean is a stateful, stateless, or singleton session bean. |
AppException |
Re-throw AppException |
Receives AppException. |
all other exceptions |
Log the exception or error. Rollback a transaction that has been started, but not yet completed, by the instance. Discard instance. Note A Throw |
Receives |
9.3.2. Exceptions from Method Invoked via Session Bean’s 2.1 Client View or through Web Service Client View
Business methods in this context are
considered to be the methods defined in the enterprise bean’s home
interface, component interface, or web service endpoint (including
superinterfaces of these); and the following session bean methods:
ejbCreate<METHOD>
, ejbRemove
, and ejbHome<METHOD>
methods.
Handling of Exceptions Thrown by Methods of Web Service Client View or Enterprise Beans 2.1 Client View of a Bean with Container-Managed Transaction Demarcation specifies how the container must handle the exceptions thrown by the business methods for beans with container-managed transaction demarcation, including the exceptions thrown by business method interceptor methods. The table specifies the container’s action as a function of the condition under which the business method executes and the exception thrown by the business method. The table also illustrates the exception that the client will receive and how the client can recover from the exception. (Client’s View of Exceptions describes the client’s view of exceptions in detail.) The notation "AppException" denotes an application exception.
Method condition | Method exception | Container’s action | Client’s view |
---|---|---|---|
Bean method runs in the context of the caller’s transaction Note A. |
AppException |
Re-throw AppException Mark the transaction for rollback if the application exception is specified as causing rollback. |
Receives AppException. Can attempt to continue computation in the
transaction, and eventually commit the transaction unless the
application exception is specified as causing rollback (the commit would
also fail if the instance called |
all other exceptions and errors |
Log the exception or error Note B. Mark the transaction for rollback. Discard instance Note C. Throw |
Receives
Continuing transaction is fruitless. |
|
Bean method runs in the context of a transaction that the container started
immediately before dispatching the business method. |
AppException |
If the instance called If the application exception is specified as causing rollback, then rollback the transaction and then re-throw AppException. Otherwise, attempt to commit the transaction, and then re-throw AppException. |
Receives AppException. If the client executes in a transaction, the client’s transaction is not marked for rollback, and client can continue its work. |
all other exceptions |
Log the exception or error. Rollback the container-started transaction. Discard instance. Throw |
Receives If the client executes in a transaction, the client’s transaction may or may not be marked for rollback. |
|
Bean method runs with an unspecified transaction context. |
AppException |
Re-throw AppException. |
Receives AppException. If the client executes in a transaction, the client’s transaction is not marked for rollback, and client can continue its work. |
all other exceptions |
Log the exception or error. Discard instance. Throw |
Receives If the client executes in a transaction, the client’s transaction may or may not be marked for rollback. |
Notes:
[A] The caller can be
another enterprise bean or an arbitrary client program. This case is not
applicable for methods of the web service endpoint.
[B] Log the exception or
error means that the container logs the exception or error so that the
System Administrator is alerted of the problem.
[C] Discard instance
means that the container must not invoke any business methods or
container callbacks on the instance. Discarding does not apply if the
bean is a singleton session bean.
[D] Throw RemoteException
to web service client means that
the container maps the RemoteException
to the appropriate SOAP fault.
See [4].
Handling of Exceptions Thrown by a Enterprise Beans 2.1 Client View Business Method of a Session Bean with Bean-Managed Transaction Demarcation specifies how the container must handle the exceptions thrown by the business methods for beans with bean-managed transaction demarcation, including the exceptions thrown by business method interceptor methods. The table specifies the container’s action as a function of the condition under which the business method executes and the exception thrown by the business method. The table also illustrates the exception that the client will receive and how the client can recover from the exception. (Client’s View of Exceptions describes the client’s view of exceptions in detail.)
Bean method condition | Bean method exception | Container action | Client receives |
---|---|---|---|
Bean is a stateful, stateless, or singleton session bean. |
AppException |
Re-throw AppException |
Receives AppException. |
all other exceptions |
Log the exception or error. Rollback a transaction that has been started, but not yet completed, by the instance. Discard instance. Note A Throw |
Receives |
Notes:
[A] Discarding does not
apply if the bean is a singleton session bean.
[B] Throw RemoteException
to web service client means
that the container maps the RemoteException
to the appropriate SOAP fault.
See [4].
9.3.3. Exceptions from AroundConstruct, PostConstruct and PreDestroy Lifecycle Callbacks
Handling of Exceptions Thrown by a PostConstruct or PreDestroy Method of a Stateful, Stateless, Singleton Session Bean or a Message-Driven Bean. specifies
how the container must handle the exceptions that escape interceptor
chain for the AroundConstruct
, PostConstruct
and PreDestroy
methods
for session and message-driven beans.
Bean method condition | Bean method exception | Container action |
---|---|---|
Bean is a stateful, stateless or singleton session bean, or a message-driven bean |
system exceptions |
Log the exception or error. If the bean is a singleton or stateful session bean, rollback any container-started transaction. Discard instance. |
9.3.4. Exceptions from Message-Driven Bean Message Listener Methods
This section specifies the container’s handling of exceptions thrown from a message-driven bean’s message listener method.
Handling of Exceptions Thrown by a Message Listener Method of a Message-Driven Bean with Container-Managed Transaction Demarcation. specifies how the container must handle the exceptions thrown by a message listener method of a message-driven bean with container-managed transaction demarcation, including the exceptions thrown by business method interceptor methods which intercept the invocation of message listener methods. The table specifies the container’s action as a function of the condition under which the method executes and the exception thrown by the method.
Method condition | Method exception | Container’s action |
---|---|---|
Bean method runs in the context of a transaction that the container started
immediately before dispatching the method. |
AppException |
Mark the transaction for rollback if the application exception is specified as causing rollback. If the instance called Otherwise, attempt to commit the transaction unless the application exception is specified as causing rollback and re-throw AppException to resource adapter. |
system exceptions |
Log the exception or error. Note A Rollback the container-started transaction. Discard instance. Note B Throw |
|
Bean method runs with an unspecified transaction context. |
AppException |
Re-throw AppException to resource adapter. |
system exceptions |
Log the exception or error. Discard instance. Throw |
Notes:
[A] Log the exception or
error means that the container logs the exception or error so that the
System Administrator is alerted of the problem.
[B] Discard instance
means that the container must not invoke any methods on the instance.
Handling of Exceptions Thrown by a Message Listener Method of a Message-Driven Bean with Bean-Managed Transaction Demarcation. specifies how the container must handle the exceptions thrown by a message listener method of a message-driven bean with bean-managed transaction demarcation. The table specifies the container’s action as a function of the condition under which the method executes and the exception thrown by the method.
Bean method condition | Bean method exception | Container action |
---|---|---|
Bean is a message-driven bean |
AppException |
Re-throw AppException to resource adapter. |
system exceptions |
Log the exception or error. Rollback a transaction that has been started, but not yet completed, by the instance. Discard instance. Throw |
9.3.5. Exceptions from an Enterprise Bean’s Timeout Callback Method
This section specifies the container’s handling of exceptions thrown from an enterprise bean’s timeout callback method.
Handling of Exceptions Thrown by a Timeout Callback Method of an Enterprise Bean with Container-Managed Transaction Demarcation. and Handling of Exceptions Thrown by a Timeout Callback Method of an Enterprise Bean with Bean-Managed Transaction Demarcation. specify how the container must handle the exceptions thrown by the timeout callback method of an enterprise bean. The timeout callback method does not throw application exceptions and cannot throw exceptions to the client.
Method condition | Method exception | Container’s action |
---|---|---|
Bean timeout callback method runs in the context of a transaction that the container started immediately before dispatching the method. |
system exceptions |
Log the exception or error. Note A Rollback the container-started transaction. Discard instance. Note B |
Notes:
[A] Log the exception or error
means that the container logs the exception or error so that the
System Administrator is alerted of the problem.
[B] Discard instance
means that the container must not invoke any methods on the instance.
Discarding does not apply if the bean is a singleton session bean.
Method condition | Method exception | Container’s action |
---|---|---|
The bean timeout callback method may make use of |
system exceptions |
Log the exception or error. Note A Rollback a transaction that has been started, but not yet completed, by the instance. Discard instance. Note B |
Notes:
[A] Log the exception or error
means that the container logs the exception or error so that the
System Administrator is alerted of the problem.
[B] Discard instance
means that the container must not invoke any methods on the instance.
Discarding does not apply if the bean is a singleton session bean.
9.3.6. Exceptions from Other Container-invoked Callbacks
This subsection specifies the container’s handling of exceptions thrown from the other container-invoked callbacks on the enterprise bean. This subsection applies to the following callback methods:
-
Dependency injection methods.
-
The
PostActivate
andPrePassivate
callback methods, and/orejbActivate
, ejbPa`ssivate, andsetSessionContext
methods of the SessionBean interface. -
The
setMessageDrivenContext
method of theMessageDrivenBean
interface. -
The
afterBegin
,beforeCompletion
andafterCompletion
session synchroniziation methods.
The container must handle all exceptions or errors from these methods as follows:
-
Log the exception or error to bring the problem to the attention of the System Administrator.
-
If the instance is in a transaction, mark the transaction for rollback.
-
Discard the instance (i.e., the container must not invoke any business methods or container callbacks on the instance).
-
If the exception or error happened during the processing of a client invoked method, throw the
jakarta.ejb.EJBException
.[64] If the Enterprise Beans 2.1 client view or web service client view is used, throw the java.rmi.RemoteException to the client if the client is a remote client or throw thejakarta.ejb.EJBException
to the client if the client is a local client. If the instance executed in the client’s transaction, the container should throw thejakarta.ejb.EJBTransactionRolledbackException
.[65] If the Enterprise Beans 2.1 client view or web service client view is used, the container should throw thejakarta.transaction.TransactionRolledbackException
to a remote client or thejakarta.ejb.TransactionRolledbackLocalException
to a local client, because it provides more information to the client. (The client knows that it is fruitless to continue the transaction.)
9.3.7. Non-existing Stateful Session Object
If a client makes a call to a stateful
session object that has been removed, the container should throw the
jakarta.ejb.NoSuchEJBException
.[66]
If the Enterprise Beans 2.1
client view is used, the container should throw the
java.rmi.NoSuchObjectException
(which is a
subclass of java.rmi.RemoteException
) to a remote client, or the
jakarta.ejb.NoSuchObjectLocalException
to a local client.
9.3.8. Exceptions from the Management of Container-Managed Transactions
The container is responsible for starting and committing the container-managed transactions, as described in Container-Managed Transaction Demarcation for Business Methods. This subsection specifies how the container must deal with the exceptions that may be thrown by the transaction start and commit operations.
If the container fails to start or commit a
container-managed transaction, the container must throw the
jakarta.ejb.EJBException
.[67]
If the web service
client view or Enterprise Beans 2.1 client view is used, the container must throw the
java.rmi.RemoteException
to a remote or web
service client and the jakarta.ejb.EJBException
to a local client. In
the case where the container fails to start or commit a
container-managed transaction on behalf of a message-driven bean or a
timeout callback method, the container must throw and log the
jakarta.ejb.EJBException
.
However, the container should not throw the
jakarta.ejb.EJBException
or java.rmi.RemoteException
if the container
performs a transaction rollback because the transaction has been marked
for rollback and no EJBException
or RemoteException
would otherwise be
thrown according to Exceptions from a Session Bean’s Business Interface Methods and No-Interface View Methods through Non-existing Stateful Session Object.
In this case, the container must rollback the
transaction and pass the business method result or the application
exception thrown by the business method to the client.
Note that some implementations of the
container may retry a failed transaction transparently to the client and
enterprise bean code. Such a container would throw the
jakarta.ejb.EJBException
or java.rmi.RemoteException
or after a
number of unsuccessful tries.
9.3.9. Release of Resources
When the container discards an instance because of a system exception, the container should release all the resources held by the instance that were acquired through the resource factories declared in the enterprise bean environment (See Resource Manager Connection Factory References).
Note: While the container should release the connections to the resource managers that the instance acquired through the resource factories declared in the enterprise bean environment, the container cannot, in general, release "unmanaged" resources that the instance may have acquired through the JDK APIs. For example, if the instance has opened a TCP/IP connection, most container implementations will not be able to release the connection. The connection will be eventually released by the JVM garbage collector mechanism.
9.3.10. Support for Deprecated Use of java.rmi.RemoteException
The Enterprise Beans 1.0
specification allowed the business methods, ejbCreate
, ejbPostCreate
,
ejbFind<METHOD>
, ejbRemove
, and the container-invoked callbacks (i.e.,
the methods defined in the SessionBean
and SessionSynchronization
interfaces) implemented in the enterprise bean class to use the
java.rmi.RemoteException
to report non-application exceptions to the
container.
This use of the java.rmi.RemoteException
was
deprecated in Enterprise Beans 1.1—enterprise beans written for the Enterprise Beans 1.1
specification should use the jakarta.ejb.EJBException
instead, and
enterprise beans written for the Enterprise Beans 2.0 or later specification must use
the jakarta.ejb.EJBException
instead.
The Enterprise Beans 1.1 and Enterprise Beans 2.0 or later
specifications require that a container support the deprecated use of
the java.rmi.RemoteException
. The container should treat the
java.rmi.RemoteException
thrown by an enterprise bean method in the same
way as it is specified for the jakarta.ejb.EJBException
.
9.4. Client’s View of Exceptions
This section describes the client’s view of exceptions received from an enterprise bean invocation.
A client accesses an enterprise bean either through the enterprise bean’s business interface (whether local or remote), through the enterprise bean’s no-interface view, through the enterprise bean’s remote home and remote component interfaces, through the enterprise bean’s local home and local component interfaces, or through the enterprise bean’s web service client view depending on whether the client is written to the Enterprise Beans 3.x API or earlier API and whether the client is a remote client, a local client, or a web service client.
The methods of the business interface
typically do not throw the java.rmi.RemoteException
, regardless of
whether the interface is a remote or local interface.
The remote home interface and the remote
component interface are Java RMI interfaces, and therefore the throws
clauses of all their methods (including those inherited from
superinterfaces) include the mandatory
java.rmi.RemoteException
. The throws
clauses may include an arbitrary number of application exceptions.
The local home and local component interfaces
are both Java local interfaces, and the throws
clauses of all their
methods (including those inherited from superinterfaces) must not
include the java.rmi.RemoteException
. The throws
clauses may include an
arbitrary number of application exceptions.
The no-interface view is a local view, and
the throws
clauses of all its methods must not include the
java.rmi.RemoteException
. The throws
clauses may include an arbitrary
number of application exceptions.
9.4.1. Application Exception
9.4.1.1. Local and Remote Clients
If a client program receives an application exception from an enterprise bean invocation, the client can continue calling the enterprise bean. An application exception does not result in the removal of the Enterprise Beans object.
Although the container does not automatically mark for rollback a transaction because of a thrown application exception, the transaction might have been marked for rollback by the enterprise bean instance before it threw the application exception or the application exception may have been specified to require the container to rollback the transaction. There are two ways to learn if a particular application exception results in transaction rollback or not:
-
Statically. Programmers can check the documentation of the enterprise bean’s client view interface. The Bean Provider may have specified (although he or she is not required to) the application exceptions for which the enterprise bean marks the transaction for rollback before throwing the exception.[68]
-
Dynamically. Clients that are enterprise beans with container-managed transaction demarcation can use the
getRollbackOnly
method of thejakarta.ejb.EJBContext
object to learn if the current transaction has been marked for rollback; other clients may use thegetStatus
method of thejakarta.transaction.UserTransaction
interface to obtain the transaction status.
9.4.1.2. Web Service Clients
If a stateless session bean throws an application exception from one of its web service methods, it is the responsibility of the container to map the exception to the SOAP fault specified in the WSDL that describes the port type that the stateless session bean implements. For Java clients, the exceptions received by the client are described by the mapping rules in [4].
9.4.2. java.rmi.RemoteException and jakarta.ejb.EJBException
As described above, a client receives the
jakarta.ejb.EJBException
or the java.rmi.RemoteException
as an
indication of a failure to invoke an enterprise bean method or to
properly complete its invocation. The exception can be thrown by the
container or by the communication subsystem between the client and the
container.
If the client receives the
jakarta.ejb.EJBException
or the
java.rmi.RemoteException
exception from a method invocation, the client,
in general, does not know if the enterprise bean’s method has been
completed or not.
If the client executes in the context of a transaction, the client’s transaction may, or may not, have been marked for rollback by the communication subsystem or target bean’s container.
For example, the transaction would be marked
for rollback if the underlying transaction service or the target bean’s
container doubted the integrity of the data because the business method
may have been partially completed. Partial completion could happen, for
example, when the target bean’s method returned with a
RuntimeException
exception, or if the remote server crashed in the
middle of executing the business method.
The transaction may not necessarily be marked for rollback. This might occur, for example, when the communication subsystem on the client-side has not been able to send the request to the server.
When a client
executing in a transaction context receives an EJBException
or a
RemoteException
from an enterprise bean invocation, the client may use
either of the following strategies to deal with the exception:
-
Discontinue the transaction. If the client is the transaction originator, it may simply rollback its transaction. If the client is not the transaction originator, it can mark the transaction for rollback or perform an action that will cause a rollback. For example, if the client is an enterprise bean, the enterprise bean may throw a
RuntimeException
which will cause the container to rollback the transaction. -
Continue the transaction. The client may perform additional operations on the same or other enterprise beans, and eventually attempt to commit the transaction. If the transaction was marked for rollback at the time the
EJBException
orRemoteException
was thrown to the client, the commit will fail.
If the client chooses to continue the
transaction, the client can first inquire about the transaction status
to avoid fruitless computation on a transaction that has been marked for
rollback. A client that is an enterprise bean with container-managed
transaction demarcation can use the EJBContext.getRollbackOnly
method to
test if the transaction has been marked for rollback; a client that is
an enterprise bean with bean-managed transaction demarcation, and other
client types, can use the UserTransaction.getStatus
method to obtain the
status of the transaction.
Some implementations of Enterprise Beans servers and
containers may provide more detailed exception reporting by throwing an
appropriate subclass of the jakarta.ejb.EJBException
or
java.rmi.RemoteException
to the client. The following subsections
describe the several subclasses of the jakarta.ejb.EJBException
and
java.rmi.RemoteException
that may be thrown by the container to give the
client more information.
9.4.2.1. jakarta.ejb.EJBTransactionRolledbackException, jakarta.ejb.TransactionRolledbackLocalException, and jakarta.transaction.TransactionRolledbackException
The
jakarta.ejb.EJBTransactionRolledbackException
and
jakarta.ejb.TransactionRolledbackLocalException
are subclasses of the
jakarta.ejb.EJBException
. The
jakarta.transaction.TransactionRolledbackException
is a subclass of the
java.rmi.RemoteException
. It is defined in the Jakarta Transactions standard extension.
If a client receives one of these exceptions, the client knows for certain that the transaction has been marked for rollback. It would be fruitless for the client to continue the transaction because the transaction can never commit.
9.4.2.2. jakarta.ejb.EJBTransactionRequiredException, jakarta.ejb.TransactionRequiredLocalException, and jakarta.transaction.TransactionRequiredException
The
jakarta.ejb.EJBTransactionRequiredException
and
jakarta.ejb.TransactionRequiredLocalException
are subclasses of the
jakarta.ejb.EJBException
. The
jakarta.transaction.TransactionRequiredException
is a subclass of the
java.rmi.RemoteException
. It is defined in the Jakarta Transactions standard extension.
The
jakarta.ejb.EJBTransactionRequiredException
,
jakarta.ejb.TransactionRequiredLocalException
, or
jakarta.transaction.TransactionRequiredException
informs the client that
the target enterprise bean must be invoked in a client’s transaction,
and that the client invoked the enterprise bean without a transaction
context.
This error usually indicates that the application was not properly formed.
9.4.2.3. jakarta.ejb.NoSuchEJBException, jakarta.ejb.NoSuchObjectLocalException, and java.rmi.NoSuchObjectException
The
jakarta.ejb.NoSuchEJBException
is a subclass of the
jakarta.ejb.EJBException
. It is thrown to the client of a session bean’s
business interface if a local business method cannot complete because
the Enterprise Beans object no longer exists.
The jakarta.ejb.NoSuchObjectLocalException
and the java.rmi.NoSuchObjectException
apply to the business methods
of the Enterprise Beans 2.1 local and remote client views respectively.
The
jakarta.ejb.NoSuchObjectLocalException
is a subclass of the
jakarta.ejb.EJBException
. It is thrown to the client if a local business
method cannot complete because the Enterprise Beans object no longer exists.
The
java.rmi.NoSuchObjectException
is a subclass of the
java.rmi.RemoteException
. It is thrown to the client if a remote
business method cannot complete because the Enterprise Beans object no longer exists.
10. Enterprise Bean Environment
This chapter specifies how enterprise beans declare dependencies on external resources and other objects in their environment, and how those items can be injected into enterprise beans or accessed in the JNDI naming context.
10.1. Overview
The Application Assembler and Deployer should be able to customize an enterprise bean’s business logic without accessing the enterprise bean’s source code.
In addition, ISVs typically develop enterprise beans that are, to a large degree, independent from the operational environment in which the application will be deployed. Most enterprise beans must access resource managers and external information. The key issue is how enterprise beans can locate external information without prior knowledge of how the external information is named and organized in the target operational environment. The JNDI naming context and Java language metadata annotations provide this capability.
The enterprise bean environment mechanism attempts to address both of the above issues.
This chapter is organized as follows:
-
Enterprise Bean’s Environment as a JNDI Naming Context defines the general rules for the use of the JNDI naming context and its interaction with Java language annotations that reference entries in the naming context.
-
Responsibilities by Enterprise Beans Role defines the general responsibilities for each of the Enterprise Beans roles, such as Bean Provider, Application Assembler, Deployer, and Container Provider.
-
Simple Environment Entries defines the basic mechanisms and interfaces that specify and access the enterprise bean’s environment. The section illustrates the use of the enterprise bean’s environment for generic customization of the enterprise bean’s business logic.
-
Enterprise Bean References defines the means for obtaining the business interface, no-interface view, or home interface of another enterprise bean using an enterprise bean reference. An enterprise bean reference is a special entry in the enterprise bean’s environment.
-
Web Service References defines the means for obtaining the web service interface using a web service reference. A web service reference is a special entry in the enterprise bean’s environment.
-
Resource Manager Connection Factory References defines the means for obtaining a resource manager connection factory using a resource manager connection factory reference. A resource manager connection factory reference is a special entry in the enterprise bean’s environment.
-
Resource Environment References defines the means for obtaining an administered object that is associated with a resource (e.g., a CCI
InteractionSpec
) using a resource environment reference . A resource environment reference is a special entry in the enterprise bean’s environment. -
Message Destination References defines the means for obtaining a message destination associated with a resource using a message destination reference. Message destination references allow the flow of messages within an application to be specified. A message destination reference is a special entry in the enterprise bean’s environment.
-
Persistence Unit References describes the means for obtaining an entity manager factory using a persistence unit reference.
-
Persistence Context References describes the means for obtaining an entity manager using a persistence context reference.
-
UserTransaction Interface describes the use by eligible enterprise beans of references to a
UserTransaction
object in the bean’s environment to start, commit, and rollback transactions. -
ORB References describes the use of references to a CORBA
ORB
object in the enterprise bean’s environment. -
TimerService References describes the means for obtaining a
TimerService
object. -
EJBContext References describes the means for obtaining a bean’s
EJBContext
object. -
Support for Other Resources and Configuration Parameters describes the requirements for other resources and configuration parameters.
10.2. Enterprise Bean’s Environment as a JNDI Naming Context
The enterprise bean’s environment is a mechanism that allows customization of the enterprise bean’s business logic during deployment or assembly. The enterprise bean’s environment allows the enterprise bean to be customized without the need to access or change the enterprise bean’s source code.
Annotations and deployment descriptors are the main vehicles for conveying access information to the Application Assembler and Deployer about beans’ requirements for customization of business logic and access to external information.
The container implements the enterprise bean’s environment, and provides it as a JNDI naming context. The enterprise bean’s environment is used as follows:
-
The enterprise bean makes use of entries from the environment. Entries from the environment may be injected by the container into the bean’s fields or methods, or the methods of the bean may access the environment using the EJBContext
lookup
method or the JNDI interfaces. The Bean Provider declares in Java language metadata annotations or in the deployment descriptor all the environment entries that the enterprise bean expects to be provided in its environment at runtime. -
The container provides an implementation of the JNDI naming context that stores the enterprise bean environment. The container also provides the tools that allow the Deployer to create and manage the environment of each enterprise bean.
-
The Deployer uses the tools provided by the container to create and initialize the environment entries that are declared by means of the enterprise bean’s annotations or deployment descriptor. The Deployer can set and modify the values of the environment entries.
-
The container injects entries from the environment into the enterprise bean’s fields or methods as specified by the bean’s metadata annotations or the deployment descriptor.
-
The container makes the environment naming context available to the enterprise bean instances at runtime. The enterprise bean’s instances can use the EJBContext
lookup
method or the JNDI interfaces to obtain the values of the environment entries.
10.2.1. Sharing of Environment Entries
For enterprise beans packaged in a standalone
ejb-jar file or in an ejb-jar file within an .ear
file, each
enterprise bean defines its own set of
environment entries. In this case, all
instances of an enterprise bean share the same environment entries; the
environment entries are not shared with other enterprise beans.
In a .war
file, there is only a single
naming environment shared between all the components in the module. For
enterprise beans packaged in a .war
file, all enterprise beans share
this single naming environment. The enterprise beans share their
environment entries with all other enterprise bean components and web
components in the .war
file.
Enterprise bean instances are not allowed to modify the bean’s environment at runtime.
Compatibility Note: If an enterprise bean written to the Enterprise Beans 2.1 API specification is deployed multiple times in the same container, each deployment results in the creation of a distinct home. The Deployer may set different values for the enterprise bean environment entries for each home.
In general, lookups of objects in the JNDI
java:
namespace are required to return a new instance of the requested
object every time. Exceptions are allowed for the following:
-
The container knows the object is immutable (for example, objects of type
java.lang.String
), or knows that the application can’t change the state of the object. -
The object is defined to be a singleton, such that only one instance of the object may exist in the JVM.
-
The name used for the lookup is defined to return an instance of the object that might be shared. The name
java:comp/ORB
is such a name.
In these cases, a shared instance of the
object may be returned. In all other cases, a new instance of the
requested object must be returned on each lookup. Note that, in the case
of resource adapter connection objects, it is the resource adapter’s
ManagedConnectionFactory
implementation that is responsible for
satisfying this requirement.
Each injection of an object corresponds to a JNDI lookup. Whether a new instance of the requested object is injected, or whether a shared instance is injected, is determined by the rules described above.
Terminology warning: The enterprise bean’s "environment" should not be confused with the "environment properties" defined in the JNDI documentation.
10.2.2. Annotations for Environment Entries
A field or method of a bean class may be
annotated to request that an entry from the bean’s environment be
injected. Any of the types of resources or other environment
entries [69] described in this chapter may be
injected. Injection may also be requested using entries in the
deployment descriptor corresponding to each of these resource types. The
field or method may have any access qualifier (public
, private
,
etc.) but must not be static
.
-
A field of the bean class may be the target of injection. The field must not be
final
. By default, the name of the field is combined with the name of the class in which the annotation is used and is used directly as the name in the bean’s naming context. For example, a field namedmyDatabase
in the classMySessionBean
in the packagecom.acme.example
would correspond to the JNDI namejava:comp/env/com.acme.example.MySessionBean/myDatabase
. The annotation also allows the JNDI name to be specified explicitly. -
Environment entries may also be injected into the bean through bean methods that follow the naming conventions for JavaBeans™ properties. The annotation is applied to the
set
method for the property, which is the method that is called to inject the environment entry. The JavaBeans property name (not the method name) is used as the default JNDI name. For example, a method namedsetMyDatabase
in the sameMySessionBean
class would correspond to the JNDI namejava:comp/env/com.example.MySessionBean/myDatabase
. -
When a deployment descriptor entry is used to specify injection, the JNDI name and the instance variable name or property name are both specified explicitly. Note that the JNDI name is always relative to the
java:comp/env
naming context.
Each resource may only be injected into a
single field or method of the bean. Requesting injection of the
java:comp/env/com.example.MySessionBean/myDatabase
resource into both
the setMyDatabase
method and the myDatabase
instance variable is an
error. Note, however, that either the field or the method could request
injection of a resource of a different (non-default) name. By explicitly
specifying the JNDI name of a resource, a single resource may be
injected into multiple fields or methods of multiple classes.
Annotations may also be applied to the bean
class itself. These annotations declare an entry in the bean’s
environment, but do not cause the resource to be injected. Instead, the
bean is expected to use the EJBContext lookup
method or the methods of
the JNDI API to lookup the entry. When the annotation is applied to the
bean class, the JNDI name and the environment entry type must be
explicitly specified.
Annotations may appear on the bean class, or on any superclass. A resource annotation on any class in the inheritance hierarchy defines a resource needed by the bean. However, injection of such resources follows the Java language overriding rules for the visibility of fields and methods. A method definition that overrides a method on a superclass defines the resource, if any, to be injected into that method. An overriding method may request injection of a different resource than is requested by the superclass, or it may request no injection even though the superclass method requests injection.
In addition, fields or methods that are not visible in or are hidden (as opposed to overridden) by a subclass may still request injection. This allows, for example, a private field to be the target of injection and that field to be used in the implementation of the superclass, even though the subclass has no visibility into that field and doesn’t know that the implementation of the superclass is using an injected resource. Note that a declaration of a field in a subclass with the same name as a field in a superclass always causes the field in the superclass to be hidden.
10.2.3. Annotations and Deployment Descriptors
Environment entries may be declared by the use of annotations, without need for any deployment descriptor entries. Environment entries may also be declared by deployment descriptor entries, without need for any annotations. The same environment entry may be declared using both an annotation and a deployment descriptor entry. In this case, the information in the deployment descriptor entry may be used to override some of the information provided in the annotation. This approach may be used by an Application Assembler to override information provided by the Bean Provider. Deployment descriptor entries should not be used to request injection of a resource into a field or method that has not been designed for injection.
The following rules apply to how a deployment
descriptor entry may override a Resource
annotation:
-
The relevant deployment descriptor entry is located based on the JNDI name used with the annotation (either defaulted or provided explicitly).
-
The type specified in the deployment descriptor must be assignable to the type of the field or property or the type specified in the
Resource
annotation. -
The description, if specified, overrides the description element of the annotation.
-
The injection target, if specified, must name exactly the annotated field or property method.
-
The
mapped-name
element, if specified, overrides the mappedName element of the annotation. -
The
res-sharing-scope
element, if specified, overrides theshareable
element of the annotation. In general, the Application Assembler or Deployer should never change the value of this element, as doing so is likely to break the application. -
The
res-auth
element, if specified, overrides theauthenticationType
element of the annotation. In general, the Application Assembler or Deployer should never change the value of this element, as doing so is likely to break the application. -
The
lookup-name
element, if specified, overrides the lookup element of the annotation.
Restrictions on the overriding of environment entry values depend on the type of environment entry.
The rules for how a deployment descriptor
entry may override an Enterprise Beans annotation are described in Enterprise Bean References.
The rules for how a deployment descriptor entry may override a
PersistenceUnit
or PersistenceContext
annotation are described in
Persistence Unit References and Persistence Context References. The rules for web services references and how
a deployment descriptor entry may override a WebServiceRef
annotation
are included in the Jakarta Enterprise Web Services specification[5].
10.3. Responsibilities by Enterprise Beans Role
This section describes the responsibilities of the various Enterprise Beans roles with regard to the specification and handling of environment entries. The sections that follow describe the responsibilities that are specific to the different types of objects that may be stored in the naming context.
10.3.1. Bean Provider’s Responsibilities
The Bean Provider may use Java language
annotations or deployment descriptor entries to request injection of a
resource from the naming context, or to declare entries that are needed
in the naming context. The Bean Provider may also use the EJBContext
lookup
method or the JNDI APIs to access entries in the naming
context. Deployment descriptor entries may also be used by the Bean
Provider to override information provided by annotations.
The enterprise bean’s environment entries are stored directly in the environment naming context, or in any of its direct or indirect subcontexts.
The value of an environment entry is of the Java type declared by the Bean Provider in the metadata annotation or deployment descriptor, or the type of the instance variable or setter method parameter of the method with which the metadata annotation is associated.
10.3.2. Application Assembler’s Responsibility
The Application Assembler is allowed to modify the values of the environment entries set by the Bean Provider, and is allowed to set the values of those environment entries for which the Bean Provider has not specified any initial values. The Application Assembler uses the deployment descriptor to override settings made by the Bean Provider, whether these were defined by the Bean Provider in the deployment descriptor or in the source code using annotations.
10.3.3. Deployer’s Responsibility
The Deployer must ensure that the values of all the environment entries declared by an enterprise bean are created and/or set to meaningful values.
The Deployer can modify the values of the environment entries that have been previously set by the Bean Provider and/or Application Assembler, and must set the values of those environment entries for which no value has been specified.
The description
elements provided by the Bean Provider or Application Assembler help the
Deployer with this task.
10.3.4. Container Provider Responsibility
The Container Provider has the following responsibilities:
-
Provide a deployment tool that allows the Deployer to set and modify the values of the enterprise bean’s environment entries.
-
Implement the
java:comp/env
,java:module
,java:app
andjava:global
environment naming contexts, and provide them to the enterprise bean instances at runtime. The naming context must include all the environment entries declared by the Bean Provider, with their values supplied in the deployment descriptor or set by the Deployer. The environment naming context must allow the Deployer to create subcontexts if they are needed by an enterprise bean. -
Inject entries from the naming environment, as specified by annotations or by the deployment descriptor.
-
The container must ensure that the enterprise bean instances have only read access to their environment variables. The container must throw the
javax.naming.OperationNotSupportedException
from all the methods of thejavax.naming.Context
interface that modify the environment naming context and its subcontexts.
10.4. Simple Environment Entries
A simple environment entry is a configuration
parameter used to customize an enterprise bean’s business logic. The
environment entry values may be one of the
following Java types: String
, Character
, Byte
, Short
, Integer
, Long
,
Boolean
, Double
, Float
, Class
, and any subclass of Enum
.
The following subsections describe the responsibilities of each Enterprise Beans role.
10.4.1. Bean Provider’s Responsibilities
This section describes the Bean Provider’s view of the bean’s environment, and defines his or her responsibilities. The first subsection describes annotations for injecting simple environment entries; the second describes the API for accessing simple environment entries; and the third describes syntax for declaring the environment entries in a deployment descriptor.
10.4.1.1. Injection of Simple Environment Entries Using Annotations
The Bean Provider uses the Resource
annotation to annotate a field or method of the bean class as a target
for the injection of a simple environment entry. The name of the
environment entry is as described in Annotations for Environment Entries; the type is as described in
Simple Environment Entries. Note that
the container will unbox the environment entry as required to match it
to a primitive type used for the injection field or method. The
authenticationType
and shareable
elements of the Resource
annotation must not be specified: simple environment entries are not
shareable and do not require authentication.
The following code example illustrates how an enterprise bean uses annotations for the injection of environment entries.
@Stateless
public class EmployeeServiceBean implements EmployeeService {
...
// The maximum number of tax exemptions, configured by Deployer
@Resource
int maxExemptions;
// The minimum number of tax exemptions, configured by Deployer
@Resource
int minExemptions;
public void setTaxInfo(int numberOfExemptions,...)
throws InvalidNumberOfExemptionsException {
...
// Use the environment entries to customize business logic.
if (numberOfExemptions > maxExemptions
|| numberOfExemptions < minExemptions)
throw new InvalidNumberOfExemptionsException();
}
}
The following code example illustrates how an environment entry can be assigned a value by referring to another entry, potentially in a different namespace.
// an entry that gets its value from an application-wide entry
@Resource(lookup="java:app/env/timeout")
int timeout;
10.4.1.2. Programming Interfaces for Accessing Simple Environment Entries
In addition to the use of injection as
described above, an enterprise bean may access environment entries
dynamically. This may be done by means of the EJBContext lookup
method
or by direct use of the JNDI interfaces. The environment entries are
declared by the Bean Provider by means of annotations on the bean class
or in the deployment descriptor.
When the JNDI interfaces are used directly,
the bean instance creates a javax.naming.InitialContext
object by
using the constructor with no arguments, and looks up the naming
environment via the InitialContext
under the name java:comp/env
.
The bean’s environmental entries are stored directly in the environment
naming context, or its direct or indirect subcontexts.
The following code example illustrates how an enterprise bean accesses its environment entries when the JNDI APIs are used directly. In this example, the names under which the entries are accessed are defined by the deployment descriptor, as shown in the example of Declaration of Simple Environment Entries in the Deployment Descriptor.
@Stateless
public class EmployeeServiceBean implements EmployeeService {
...
public void setTaxInfo(int numberOfExemptions, ...)
throws InvalidNumberOfExemptionsException {
...
// Obtain the enterprise bean’s environment naming context.
Context initCtx = new InitialContext();
Context myEnv = (Context)initCtx.lookup("java:comp/env");
// Obtain the maximum number of tax exemptions
// configured by the Deployer.
Integer maxExemptions = (Integer)myEnv.lookup("maxExemptions");
// Obtain the minimum number of tax exemptions
// configured by the Deployer.
Integer minExemptions = (Integer)myEnv.lookup("minExemptions");
// Use the environment entries to customize business logic.
if (numberOfExeptions > maxExemptions
|| numberOfExemptions < minExemptions)
throw new InvalidNumberOfExemptionsException();
// Get some more environment entries. These environment
// entries are stored in subcontexts.
String val1 = (String)myEnv.lookup("foo/name1");
Boolean val2 = (Boolean)myEnv.lookup("foo/bar/name2");
// The enterprise bean can also lookup using full pathnames.
Integer val3 = (Integer)initCtx.lookup("java:comp/env/name3");
Integer val4 = (Integer)initCtx.lookup("java:comp/env/foo/name4");
...
}
}
10.4.1.3. Declaration of Simple Environment Entries in the Deployment Descriptor
The Bean Provider
must declare all the simple environment entries accessed from the
enterprise bean’s code. The simple environment entries are declared
either using annotations in the bean class code or using the env-entry
elements in the deployment descriptor.
Each env-entry
deployment descriptor element
describes a single environment entry. The env-entry
element consists of
an optional description of the environment entry, the environment entry
name relative to the java:comp/env
context, the expected Java type of
the environment entry value (i.e., the type of the object returned from
the EJBContext or JNDI lookup
method), and an optional environment entry
value.
See Sharing of Environment Entries for environment entry name scoping rules.
If the Bean Provider provides a value for an
environment entry using the env-entry-value
element, the value can be
changed later by the Application Assembler or Deployer. The value must
be a string that is valid for the constructor of the specified type that
takes a single String
parameter, or for java.lang.Character
, a single
character.
The following example is the declaration of
environment entries used by the EmployeeServiceBean
whose code was
illustrated in the previous subsection.
<enterprise-beans>
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<env-entry>
<description>
The maximum number of tax exemptions
allowed to be set.
</description>
<env-entry-name>maxExemptions</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>15</env-entry-value>
</env-entry>
<env-entry>
<description>
The minimum number of tax exemptions
allowed to be set.
</description>
<env-entry-name>minExemptions</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>1</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>foo/name1</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>value1</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>foo/bar/name2</env-entry-name>
<env-entry-type>java.lang.Boolean</env-entry-type>
<env-entry-value>true</env-entry-value>
</env-entry>
<env-entry>
<description>Some description.</description>
<env-entry-name>name3</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
</env-entry>
<env-entry>
<env-entry-name>foo/name4</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>10</env-entry-value>
</env-entry>
...
</session>
</enterprise-beans>
Injection of environment entries may also be specified using the deployment descriptor, without need for Java language annotations. The following is an example of the declaration of environment entries corresponding to the example of Injection of Simple Environment Entries Using Annotations.
<enterprise-beans>
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<env-entry>
<description>
The maximum number of tax exemptions
allowed to be set.
</description>
<env-entry-name>
com.wombat.empl.EmployeeService/maxExemptions
</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>15</env-entry-value>
<injection-target>
<injection-target-class>
com.wombat.empl.EmployeeServiceBean
</injection-target-class>
<injection-target-name>maxExemptions</injection-target-name>
</injection-target>
</env-entry>
<env-entry>
<description>
The minimum number of tax exemptions
allowed to be set.
</description>
<env-entry-name>
com.wombat.empl.EmployeeService/minExemptions
</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>1</env-entry-value>
<injection-target>
<injection-target-class>
com.wombat.empl.EmployeeServiceBean
</injection-target-class>
<injection-target-name>minExemptions</injection-target-name>
</injection-target>
</env-entry>
...
</session>
</enterprise-beans>
It is often convenient to declare a field as an injection target, but to specify a default value in the code, as illustrated in the following example.
// The maximum number of tax exemptions, configured by the Deployer.
@Resource
int maxExemptions = 4; // defaults to 4
To support this case, the container must only
inject a value for the environment entry if the Application Assembler or
Deployer has specified a value to override the default value. The
env-entry-value
element in the deployment descriptor is optional when
an injection target is specified. If the element is not specified, no
value will be injected. In addition, if the element is not specified,
the named resource is not initialized in the naming context, and
explicit lookups of the named resource will fail.
The deployment descriptor equivalent of the
lookup
element of the Resource
annotation is lookup-name
. The following
deployment descriptor fragment is equivalent to the earlier example that
used lookup
.
<env-entry>
<env-entry-name>
com.wombat.empl.EmployeeServiceBean/timeout
</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<injection-target>
<injection-target-class>
com.wombat.empl.EmployeeServiceBean
</injection-target-class>
<injection-target-name>timeout</injection-target-name>
</injection-target>
<lookup-name>java:app/env/timeout</lookup-name>
</env-entry>
It is an error for both the env-entry-value
and lookup-name
elements to be specified for a given env-entry element.
If either element exists, an eventual lookup element of the
corresponding Resource
annotation (if any) must be ignored. In other
words, assignment of a value to an environment entry via a deployment
descriptor, either directly (env-entry-value
) or indirectly
(lookup-name
), overrides any assignments made via annotations.
10.4.2. Application Assembler’s Responsibility
The Application Assembler is allowed to modify the values of the simple environment entries set by the Bean Provider, and is allowed to set the values of those environment entries for which the Bean Provider has not specified any initial values. The Application Assembler may use the deployment descriptor to override settings made by the Bean Provider, whether in the deployment descriptor or using annotations.
10.4.3. Deployer’s Responsibility
The Deployer must ensure that the values of all the simple environment entries declared by an enterprise bean are set to meaningful values.
The Deployer can modify the values of the environment entries that have been previously set by the Bean Provider and/or Application Assembler, and must set the values of those environment entries for which no value has been specified.
The description
elements provided by the Bean Provider or Application Assembler help the
Deployer with this task.
10.4.4. Container Provider Responsibility
The Container Provider has the following responsibilities:
-
Provide a deployment tool that allows the Deployer to set and modify the values of the enterprise bean’s environment entries.
-
Implement the
java:comp/env
,java:module
,java:app
andjava:global
environment naming contexts, and provide them to the enterprise bean instances at runtime. The naming context must include all the environment entries declared by the Bean Provider, with their values supplied in the deployment descriptor or set by the Deployer. The environment naming context must allow the Deployer to create subcontexts if they are needed by an enterprise bean. -
Inject entries from the naming environment into the bean instance, as specified by the annotations on the bean class or by the deployment descriptor.
-
The container must ensure that the enterprise bean instances have only read access to their environment variables. The container must throw the
javax.naming.OperationNotSupportedException
from all the methods of thejavax.naming.Context
interface that modify the environment naming context and its subcontexts.
10.5. Enterprise Bean References
This section describes the programming and deployment descriptor interfaces that allow the Bean Provider to refer to the business interfaces, no-interface views, or home interfaces of other enterprise beans using "logical" names called enterprise bean references. The enterprise bean references are special entries in the enterprise bean’s environment. The Deployer binds the enterprise bean references to the enterprise bean business interfaces, no-interface views, or home interfaces in the target operational environment, as appropriate.
The deployment descriptor also allows the Application Assembler to link an enterprise bean reference declared in one enterprise bean to another enterprise bean contained in the same ejb-jar file, or in another ejb-jar file in the same Jakarta EE application unit. The link is an instruction to the tools used by the Deployer that the enterprise bean reference should be bound to the business interface, no-interface view, or home interface of the specified target enterprise bean. This linking can also be specified by the Bean Provider using annotations in the source code of the bean class.
10.5.1. Bean Provider’s Responsibilities
This section describes the Bean Provider’s view and responsibilities with respect to enterprise bean references. The first subsection describes annotations for injecting enterprise bean references; the second describes the API for accessing enterprise bean references; and the third describes syntax for declaring the enterprise bean references in a deployment descriptor.
10.5.1.1. Injection of Enterprise Bean References
The Bean Provider uses the EJB
annotation
to annotate a field or setter property method of the bean class as a
target for the injection of an enterprise bean reference.
EJB
annotation contains the following
elements:
-
The
name
element refers to the name by which the resource is to be looked up in the environment. -
The
beanInterface
element is the referenced interface type. The reference may be to a session bean’s business interface, to a session bean’s no-interface view, or to the local home interface or remote home interface of a session bean or an entity bean.[70] -
The
beanName
element references the value of the name element of theStateful
orStateless
annotation (orejb-name
element, if the deployment descriptor was used to define the name of th bean). ThebeanName
element allows disambiguation if multiple session beans in the ejb-jar implement the same interface. -
The
mappedName
element is a product-specific name that the bean reference should be mapped to. Applications that use mapped names may not be portable. -
The
lookup
element is a portable lookup string containing the JNDI name for the target enterprise bean component.
Either the beanName
or the lookup
element can
be used to resolve the enterprise bean dependency to the target component. It is an
error to specify values for both beanName
and lookup
.
The following example illustrates how an
enterprise bean uses the EJB
annotation to reference another
enterprise bean. The enterprise bean reference will have the name
java:comp/env/com.acme.example.ExampleBean/myCart
in the referencing
bean’s naming context, where ExampleBean
is the name of the class of
the referencing bean and com.acme.example
its package. The target of
the reference must be resolved by the Deployer, unless there is only one
session bean component within the same application that exposes a client
view type which matches the enterprise bean reference.
package com.acme.example;
@Stateless
public class ExampleBean implements Example {
...
@EJB
private ShoppingCart myCart;
...
}
The following example illustrates use of
almost all portable elements of the EJB
annotation. In this case, the
enterprise bean reference would have the name
java:comp/env/ejb/shopping-cart
in the referencing bean’s naming
context. This reference is linked to a bean named cart1
.
@EJB(
name="ejb/shopping-cart",
beanInterface=ShoppingCart.class,
beanName="cart1",
description="The shopping cart for this application"
)
private ShoppingCart myCart;
As an alternative to beanName
, a reference
to an enterprise bean can use a session bean JNDI name by means of the lookup
annotation element. The following example uses a JNDI name in the
application namespace.
@EJB(
lookup="java:app/cartModule/ShoppingCart",
description="The shopping cart for this application"
)
private ShoppingCart myOtherCart;
If the ShoppingCart
bean were instead
written to the Enterprise Beans 2.1 client view, the enterprise bean reference would be to the
bean’s home interface. For example:
@EJB(
name="ejb/shopping-cart",
beanInterface=ShoppingCartHome.class,
beanName="cart1",
description="The shopping cart for this application"
)
private ShoppingCartHome myCartHome;
If the ShoppingCart
bean were instead
written to the no-interface client view and was implemented by bean
class ShoppingCartBean.class
, the EJB reference would have type
ShoppingCartBean.class
. For example:
@EJB(
name="ejb/shopping-cart",
beanInterface=ShoppingCartBean.class,
beanName="cart1",
description="The shopping cart for this application"
)
private ShoppingCartBean myCart;
10.5.1.2. Enterprise Bean Reference Programming Interfaces
The Bean Provider may use enterprise bean references to locate the business interfaces, no-interface views, or home interfaces of other enterprise beans as follows.
-
Assign an entry in the enterprise bean’s environment to the reference. (See Declaration of Enterprise Bean References in Deployment Descriptor for information on how enterprise bean references are declared in the deployment descriptor.)
-
The Enterprise Beans specification recommends, but does not require, that all references to other enterprise beans be organized in the
ejb
subcontext of the bean’s environment (i.e., in thejava:comp/env/ejb
JNDI context). Note that enterprise bean references declared by means of annotations will not, by default, be in any subcontext. -
Look up the business interface, no-interface view, or home interface of the referenced enterprise bean in the enterprise bean’s environment using the EJBContext
lookup
method or the JNDI API.
The following example illustrates how an enterprise bean uses an enterprise bean reference to locate the remote home interface of another enterprise bean using the JNDI APIs.
@EJB(name="ejb/EmplRecord", beanInterface=EmployeeRecordHome.class)
@Stateless
public class EmployeeServiceBean
implements EmployeeService {
public void changePhoneNumber(...) {
...
// Obtain the default initial JNDI context.
Context initCtx = new InitialContext();
// Look up the home interface of the EmployeeRecord
// enterprise bean in the environment.
Object result = initCtx.lookup(
"java:comp/env/ejb/EmplRecord");
// Convert the result to the proper type.
EmployeeRecordHome emplRecordHome = (EmployeeRecordHome)
javax.rmi.PortableRemoteObject.narrow(result,
EmployeeRecordHome.class);
...
}
}
In the example, the Bean Provider of the
EmployeeServiceBean
enterprise bean assigned the environment entry
ejb/EmplRecord
as the enterprise bean reference name to refer to the remote home of
another enterprise bean.
10.5.1.3. Declaration of Enterprise Bean References in Deployment Descriptor
Although the enterprise bean
reference is an entry in the enterprise bean’s environment, the Bean
Provider must not use a env-entry
element to declare it. Instead, the
Bean Provider must declare all the enterprise bean references using the ejb-ref
and
ejb-local-ref
elements of the deployment descriptor. This allows the
ejb-jar consumer (i.e. Application Assembler or Deployer) to discover
all the enterprise bean references used by the enterprise bean. Deployment
descriptor entries may also be used to specify injection of an enterprise bean
reference into a bean.
Each ejb-ref
or ejb-local-ref
element describes the interface
requirements that the referencing enterprise bean has for the referenced
enterprise bean. The ejb-ref
element is used for referencing an
enterprise bean that is accessed through its remote business interface
or remote home and component interfaces. The ejb-local-ref
element is used for referencing an
enterprise bean that is accessed through its local business interface,
no-interface view, local home and component interfaces.
The ejb-ref
element contains the description
,
ejb-ref-name
, ejb-ref-type
, home
, remote
, ejb-link
, and lookup-name
elements.
The ejb-local-ref
element contains the
description
, ejb-ref-name
, ejb-ref-type
, local-home
, local
, ejb-link
,
and lookup-name
elements.
The ejb-ref-name
element specifies the enterprise bean reference name: its value is the environment
entry name used in the enterprise bean code. The ejb-ref-name
must be
specified.
The optional
ejb-ref-type
element specifies the expected
type of the enterprise bean: its value must be either
Entity [71] or Session.
The home
and remote
or local-home
and local
elements specify the expected Java types of the referenced enterprise
bean’s interface(s). If the reference is to an Enterprise Beans 2.1 remote client
view interface, the home
element is required. Likewise, if the
reference is to an Enterprise Beans 2.1 local client view interface, the local-home
element is required. The remote
element of the ejb-ref
element
refers to either the remote business interface type or the remote
component interface, depending on whether the reference is to a bean’s
Enterprise Beans 3.x or Enterprise Beans 2.1 remote client view. Likewise, the local
element of
the ejb-local-ref
element refers to either the local business
interface type, bean class type or the local component interface type,
depending on whether the reference is to a bean’s Enterprise Beans 3.x local business
interface, no-interface view, or Enterprise Beans 2.1 local client view respectively.
The ejb-link
element is used to like an enterprise bean
reference to a target bean, and is described in Application Assembler’s Responsibilities below.
The lookup-name
element specifies the JNDI
name of the enterprise bean reference’s target session bean, and is described
further in Application Assembler’s Responsibilities below.
See Sharing of Environment Entries for the name scoping rules of enterprise bean references.
The following example illustrates the declaration of enterprise bean references in the deployment descriptor.
...
<enterprise-beans>
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<ejb-ref>
<description>
This is a reference to an Enterprise Beans 2.1 session
bean that encapsulates access to employee records.
</description>
<ejb-ref-name>ejb/EmplRecord</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>com.wombat.empl.EmployeeRecordHome</home>
<remote>com.wombat.empl.EmployeeRecord</remote>
</ejb-ref>
<ejb-local-ref>
<description>
This is a reference to the local business interface
of an Enterprise Beans 3.0 session bean that provides a payroll
service.
</description>
<ejb-ref-name>ejb/Payroll</ejb-ref-name>
<local>com.aardvark.payroll.Payroll</local>
</ejb-local-ref>
<ejb-local-ref>
<description>
This is a reference to the local business interface
of an Enterprise Beans 3.0 session bean that provides a pension
plan service.
</description>
<ejb-ref-name>ejb/PensionPlan</ejb-ref-name>
<local>com.wombat.empl.PensionPlan</local>
</ejb-local-ref>
...
</session>
...
</enterprise-beans>
...
10.5.2. Application Assembler’s Responsibilities
The Application
Assembler can use the ejb-link
element in the deployment descriptor to
link an enterprise bean reference to a target enterprise bean within the same
application.
The Application Assembler specifies the link between two enterprise beans as follows:
-
The Application Assembler uses the optional
ejb-link
element of theejb-ref
orejb-local-ref
element of the referencing enterprise bean. The value of theejb-link
element is the name of the target enterprise bean. (This is the bean name as defined by metadata annotation (or default) in the bean class or in theejb-name
element of the target enterprise bean.) The target enterprise bean can be in any ejb-jar file or.war
file in the same Jakarta EE application as the referencing application component. -
Alternatively, to avoid the need to rename enterprise beans to have unique names within an entire Jakarta EE application, the Application Assembler may use either of the following two syntaxes in the
ejb-link
element of the referencing application component.[72]-
The Application Assembler specifies the module name of the ejb-jar file or
.war
file containing the referenced enterprise bean and appends the ejb-name of the target bean separated by/
. The module name is the name of the module in which the enterprise bean is packaged, with no filename extension, unless themodule-name
element is specified in the module’s deployment descriptor. -
The Application Assembler specifies the path name of the ejb-jar file or
.war
file containing the referenced enterprise bean and appends the ejb-name of the target bean separated from the path name by#
. The path name is relative to the referencing application component jar file. In this manner, multiple beans with the same ejb-name may be uniquely identified when the Application Assembler cannot change ejb-names.
-
-
Rather than using
ejb-link
to resolve the enterprise bean reference, the Application Assembler may use thelookup-name
element to reference the target enterprise bean component by means of one of its JNDI names. It is an error for both ejb-link andlookup-name
to be specified within anejb-ref
orejb-local-ref
element. -
The Application Assembler must ensure that the target enterprise bean is type-compatible with the declared enterprise bean reference. This means that the target enterprise bean must be of the type indicated in the
ejb-ref-type
element, if present, and that the business interface, bean class, or home and component interfaces of the target enterprise bean must be Java type-compatible with the type declared in the enterprise bean reference.
The following illustrates the use of an ejb-link in the deployment descriptor.
...
<enterprise-beans>
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<ejb-ref>
<ejb-ref-name>ejb/EmplRecord</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>com.wombat.empl.EmployeeRecordHome</home>
<remote>com.wombat.empl.EmployeeRecord</remote>
<ejb-link>EmployeeRecord</ejb-link>
</ejb-ref>
...
</session>
...
<session>
<ejb-name>EmployeeRecord</ejb-name>
<home>com.wombat.empl.EmployeeRecordHome</home>
<remote>com.wombat.empl.EmployeeRecord</remote>
...
</session>
...
</enterprise-beans>
...
The Application Assembler uses the ejb-link
element to indicate that the enterprise bean reference EmplRecord
declared in the
EmployeeService
enterprise bean has been linked to the
EmployeeRecord
enterprise bean.
The following example illustrates using the
ejb-link
element to indicate an enterprise bean reference to the
ProductEJB
enterprise bean that is in the same Jakarta EE application unit
but in a different ejb-jar file.
<session>
...
<ejb-name>OrderEJB</ejb-name>
<ejb-class>com.wombat.orders.OrderBean</ejb-class>
...
<ejb-ref>
<ejb-ref-name>ejb/Product</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>com.acme.orders.ProductHome</home>
<remote>com.acme.orders.Product</remote>
<ejb-link>../products/product.jar#ProductEJB</ejb-link>
</ejb-ref>
...
</session>
The following example illustrates using the
ejb-link
element to indicate an enterprise bean reference to the
ShoppingCart
enterprise bean that is in the same Jakarta EE application
unit but in a different ejb-jar file. The reference was originally
declared in the bean’s code using an annotation. The Application
Assembler provides only the link to the bean.
...
<ejb-ref>
<ejb-ref-name>ShoppingService/myCart</ejb-ref-name>
<ejb-link>product/ShoppingCart</ejb-link>
</ejb-ref>
...
The same effect can be obtained with the
lookup-name
element instead, using an appropriate JNDI name for the
target bean.
...
<ejb-ref>
<ejb-ref-name>ShoppingService/myCart</ejb-ref-name>
<lookup-name>java:app/products/ShoppingCart</lookup-name>
</ejb-ref>
...
10.5.2.1. Overriding Rules
The following rules apply to how a deployment
descriptor entry may override an EJB
annotation:
-
The relevant deployment descriptor entry is located based on the JNDI name used with the annotation (either defaulted or provided explicitly).
-
The type specified in the deployment descriptor via the
remote
,local
,remote-home
, orlocal-home
element and any bean referenced by theejb-link
element must be assignable to the type of the field or property or the type specified by thebeanInterface
element of theEJB
annotation. -
The description, if specified, overrides the description element of the annotation.
-
The injection target, if specified, must name exactly the annotated field or property method.
10.5.3. Deployer’s Responsibility
The Deployer is responsible for the following:
-
The Deployer must ensure that all the declared enterprise bean references are bound to the business interfaces, no-interface views, or home interfaces of enterprise beans that exist in the operational environment. For session beans, the Deployer may use the information provided by the Bean Provider in the mappedName element of the
EJB
annotation or the mapped-name element of theejb-ref
orejb-local-ref
deployment descriptor element in creating this binding. Access in the Global JNDI Namespace describes the syntax for session bean portable global JNDI names. The Deployer may also use, for example, the JNDILinkRef
mechanism to create a symbolic link to the actual JNDI name of the target enterprise bean. -
The Deployer must ensure that the target enterprise bean is type-compatible with the types declared for the enterprise bean reference. This means that the target enterprise bean must be of the type indicated by the use of the
EJB
annotation, by theejb-ref-type
element (if specified), and that the business interface, no-interface view, and/or home and component interfaces of the target enterprise bean must be Java type-compatible with the type of the injection target or the types declared in the enterprise bean reference. -
If an
EJB
annotation includes thebeanName
element or theejb-ref
orejb-local-ref
element includes theejb-link
element, the Deployer should bind the enterprise bean reference to the enterprise bean specified as the target. -
If an
EJB
annotation includes the lookup element or the theejb-ref
orejb-local-ref
element includes thelookup-name
element, the Deployer should bind the enterprise bean reference to the enterprise bean specified as the target. It is an error for an enterprise bean reference declaration to include both anejb-link
and alookup-name
element.
The following example illustrates the use of
the lookup-name
element to bind an enterprise bean reference to a target enterprise
bean in the operational environment. The reference was originally
declared in the bean’s code using an annotation. The target enterprise
bean has ejb-name ShoppingCart
and is deployed in the stand-alone module
products.jar
.
...
<ejb-ref>
<ejb-ref-name>ShoppingService/myCart</ejb-ref-name>
<lookup-name>java:global/products/ShoppingCart</lookup-name>
</ejb-ref>
10.5.4. Container Provider’s Responsibility
The Container Provider must provide the
deployment tools that allow the Deployer to perform the tasks described
in the previous subsection. The deployment
tools provided by the Container Provider must be able to process the
information supplied in the ejb-ref
and ejb-local-ref
elements in the
deployment descriptor.
At the minimum, the tools must be able to:
-
Preserve the application assembly information in annotations or in the
ejb-link
elements by binding an enterprise bean reference to the business interface, no-interface view, or the home interface of the specified target bean. -
Inform the Deployer of any unresolved enterprise bean references, and allow him or her to resolve an enterprise bean reference by binding it to a specified compatible target bean.
10.6. Web Service References
Web service references allow the Bean Provider to refer to external web services. The web service references are special entries in the enterprise bean’s environment. The Deployer binds the web service references to the web service classes or interfaces in the target operational environment.
The specification of web service references and their usage is defined in the Jakarta XML Web Services [4] and Jakarta Enterprise Web Services specifications[5].
See Sharing of Environment Entries for the name scoping rules of web service references.
The Enterprise Beans specification recommends, but does
not require, that all references to web services be organized in the
service
subcontext of the bean’s environment (i.e., in the
java:comp/env/service
JNDI context).
10.7. Resource Manager Connection Factory References
A resource
manager connection factory is an object that is used to create
connections to a resource manager. For example, an object that
implements the javax.sql.DataSource
interface is a resource manager
connection factory for java.sql.Connection
objects that implement
connections to a database management system.
This section describes the metadata annotations and deployment descriptor elements that allow the enterprise bean code to refer to resource factories using logical names called resource manager connection factory references. The resource manager connection factory references are special entries in the enterprise bean’s environment. The Deployer binds the resource manager connection factory references to the actual resource manager connection factories that are configured in the container. Because these resource manager connection factories allow the container to affect resource management, the connections acquired through the resource manager connection factory references are called managed resources (e.g., these resource manager connection factories allow the container to implement connection pooling and automatic enlistment of the connection with a transaction).
10.7.1. Bean Provider’s Responsibilities
This subsection describes the Bean Provider’s view of locating resource factories and defines his or her responsibilities. The first subsection describes annotations for injecting references to resource manager connection factories; the second describes the API for accessing resource manager connection references; and the third describes syntax for declaring the resource manager connection references in a deployment descriptor.
10.7.1.1. Injection of Resource Manager Connection Factory References
A field or a method of an enterprise bean may
be annotated with the Resource
annotation. The name and type of the
factory are as described above in Annotations for Environment Entries. The authenticationType
and
shareable
elements of the Resource
annotation may be used to control
the type of authentication desired for the resource and the shareability
of connections acquired from the factory, as described in the following
sections.
The following code example illustrates how an enterprise bean uses annotations to declare resource manager connection factory references.
//The employee database.
@Resource
javax.sql.DataSource employeeAppDB;
...
public void changePhoneNumber(...) {
...
// Invoke factory to obtain a resource. The security
// principal for the resource is not given, and
// therefore it will be configured by the Deployer.
java.sql.Connection con = employeeAppDB.getConnection();
...
}
The same resource manager can be declared using the JNDI name of an entry to which the resource being defined will be bound.
// The customer database, looked up in the application environment.
@Resource(lookup="java:app/env/employeeAppDB")
javax.sql.DataSource employeeAppDB;
10.7.1.2. Programming Interfaces for Resource Manager Connection Factory References
The Bean Provider must use resource manager connection factory references to obtain connections to resources as follows.
-
Assign an entry in the enterprise bean’s environment to the resource manager connection factory reference. (See Declaration of Resource Manager Connection Factory References in Deployment Descriptor for information on how resource manager connection factory references are declared in the deployment descriptor.)
-
The Enterprise Beans specification recommends, but does not require, that all resource manager connection factory references be organized in the subcontexts of the bean’s environment, using a different subcontext for each resource manager type. For example, all JDBC data source references might be declared in the
java:comp/env/jdbc
subcontext, and all Jakarta Messaging connection factories in thejava:comp/env/jms
subcontext. Also, all Jakarta® Mail connection factories might be declared in thejava:comp/env/mail
subcontext and all URL connection factories in thejava:comp/env/url
subcontext. Note that resource manager connection factory references declared via annotations will not, by default, appear in any subcontext. -
Lookup the resource manager connection factory object in the enterprise bean’s environment using the EJBContext
lookup
method or using the JNDI API. -
Invoke the appropriate method on the resource manager connection factory to obtain a connection to the resource. The factory method is specific to the resource type. It is possible to obtain multiple connections by calling the factory object multiple times.
The Bean Provider can control the
shareability of the connections acquired from the resource manager
connection factory. By default, connections
to a resource manager are shareable across
other enterprise beans in the application that use the same resource in
the same transaction context. The Bean Provider can specify that
connections obtained from a resource manager connection factory
reference are not shareable by specifying the value of the shareable
annotation element to false
or the value of the res-sharing-scope
deployment descriptor element to be
Unshareable
. The sharing of connections to a resource manager allows
the container to optimize the use of connections and enables the
container’s use of local transaction optimizations.
The Bean Provider has two choices with respect to dealing with associating a principal with the resource manager access:
-
Allow the Deployer to set up principal mapping or resource manager sign-on information. In this case, the enterprise bean code invokes a resource manager connection factory method that has no security-related parameters.
-
Sign on to the resource manager from the bean code. In this case, the enterprise bean invokes the appropriate resource manager connection factory method that takes the sign-on information as method parameters.
The Bean Provider
uses the authenticationType
annotation element or the res-auth
deployment descriptor element to indicate which of the two
resource manager authentication approaches
is used.
We expect that the first form (i.e., letting the Deployer set up the resource manager sign-on information) will be the approach used by most enterprise beans.
The following code sample illustrates
obtaining a JDBC connection when the EJBContext lookup
method is used.
@Resource(name="jdbc/EmployeeAppDB", type=javax.sql.DataSource)
@Stateless
public class EmployeeServiceBean implements EmployeeService {
@Resource
SessionContext ctx;
public void changePhoneNumber(...) {
...
// use context lookup to obtain resource manager
// connection factory
javax.sql.DataSource ds = (javax.sql.DataSource)
ctx.lookup("jdbc/EmployeeAppDB");
// Invoke factory to obtain a connection. The security
// principal is not given, and therefore
// it will be configured by the Deployer.
java.sql.Connection con = ds.getConnection();
...
}
}
The following code sample illustrates obtaining a JDBC connection when the JNDI APIs are used directly.
@Resource(name="jdbc/EmployeeAppDB", type=javax.sql.DataSource)
@Stateless
public class EmployeeServiceBean implements EmployeeService {
EJBContext ejbContext;
public void changePhoneNumber(...) {
...
// obtain the initial JNDI context
Context initCtx = new InitialContext();
// perform JNDI lookup to obtain resource manager
// connection factory
javax.sql.DataSource ds = (javax.sql.DataSource)
initCtx.lookup("java:comp/env/jdbc/EmployeeAppDB");
// Invoke factory to obtain a connection. The security
// principal is not given, and therefore
// it will be configured by the Deployer.
java.sql.Connection con = ds.getConnection();
...
}
}
10.7.1.3. Declaration of Resource Manager Connection Factory References in Deployment Descriptor
Although a resource manager connection
factory reference is an entry in the enterprise bean’s environment, the
Bean Provider must not use an env-entry
element to declare it.
Instead, if metadata annotations are not
used, the Bean Provider must declare all the resource manager connection
factory references in the deployment descriptor using the
resource-ref
elements. This allows the
ejb-jar consumer (i.e. Application Assembler or Deployer) to discover
all the resource manager connection factory references used by an
enterprise bean. Deployment descriptor entries may also be used to
specify injection of a resource manager connection factor reference into
a bean.
See Section "Declaration of Resource Manager
Connection Factory References in Deployment Descriptor" in the
Jakarta EE Platform specification [18] for the description of the
resource-ref
element.
See Sharing of Environment Entries for the name scoping rules of resource manager connection factory references.
The type declaration allows the Deployer to identify the type of the resource manager connection factory.
Note that the indicated type is the Java type of the resource factory, not the Java type of the resource.
The following example is the declaration of
resource manager connection factory references used by the
EmployeeService
enterprise bean illustrated in the previous subsection.
...
<enterprise-beans>
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<resource-ref>
<description>
A data source for the database in which
the EmployeeService enterprise bean will
record a log of all transactions.
</description>
<res-ref-name>jdbc/EmployeeAppDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
...
</session>
</enterprise-beans>
...
The following example illustrates the declaration of Jakarta Messaging resource manager connection factory references.
...
<enterprise-beans>
<session>
...
<resource-ref>
<description>
A queue connection factory used by the
MySession enterprise bean to send
notifications.
</description>
<res-ref-name>jms/qConnFactory</res-ref-name>
<res-type>jakarta.jms.QueueConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Unshareable</res-sharing-scope>
</resource-ref>
...
</session>
</enterprise-beans>
...
10.7.1.4. Standard Resource Manager Connection Factory Types
The Bean Provider must use the
javax.sql.DataSource
resource manager connection factory type for
obtaining JDBC connections, and the
jakarta.jms.ConnectionFactory
,
jakarta.jms.QueueConnectionFactory
, or jakarta.jms.TopicConnectionFactory
for obtaining Jakarta Messaging connections.
The Bean Provider must use the
jakarta.mail.Session
resource manager
connection factory type for obtaining
Jakarta Mail connections, and the java.net.URL
resource manager connection factory type
for obtaining URL connections.
It is recommended that the Bean Provider
names JDBC data sources in the java:comp/env/jdbc
subcontext, and Jakarta Messaging
connection factories in the java:comp/env/jms
subcontext. It is also
recommended that the Bean Provider name all Jakarta Mail connection
factories in the java:comp/env/mail
subcontext, and all URL connection
factories in the java:comp/env/url
subcontext. Note that resource
manager connection factory references declared via annotations will not,
by default, appear in any subcontext.
Jakarta® Connectors [16] allows an enterprise bean to use the API described in this section to obtain resource objects that provide access to additional back-end systems.
10.7.2. Deployer’s Responsibility
The Deployer uses deployment tools to bind the resource manager connection factory references to the actual resource factories configured in the target operational environment.
The Deployer must perform the following tasks for each resource manager connection factory reference declared in the metadata annotations or deployment descriptor:
-
Bind the resource manager connection factory reference to a resource manager connection factory that exists in the operational environment. The Deployer may use, for example, the JNDI
LinkRef
mechanism to create a symbolic link to the actual JNDI name of the resource manager connection factory. The resource manager connection factory type must be compatible with the type declared in the source code or in theres-type
element. -
Provide any additional configuration information that the resource manager needs for opening and managing the resource. The configuration mechanism is resource-manager specific, and is beyond the scope of this specification.
-
If the value of the
Resource
annotationauthenticationType
element isAuthenticationType.CONTAINER
or the deployment descriptorres-auth
element is Container, the Deployer is responsible for configuring the sign-on information for the resource manager. This is performed in a manner specific to the Enterprise Beans container and resource manager; it is beyond the scope of this specification.
For example, if principals must be mapped from the security domain and principal realm used at the enterprise beans application level to the security domain and principal realm of the resource manager, the Deployer or System Administrator must define the mapping. The mapping is performed in a manner specific to the Enterprise Beans container and resource manager; it is beyond the scope of the current Enterprise Beans specification.
10.7.3. Container Provider Responsibility
The Container Provider is responsible for the following:
-
Provide the deployment tools that allow the Deployer to perform the tasks described in the previous subsection.
-
Provide the implementation of the resource manager connection factory classes for the resource managers that are configured with the Enterprise Beans container.
-
If the Bean Provider sets the
authenticationType
element of theResource
annotation toAuthenticationType.APPLICATION
or theres-auth
deployment descriptor entry for a resource manager connection factory reference to Application, the container must allow the bean to perform explicit programmatic sign-on using the resource manager’s API. -
If the Bean Provider sets the
shareable
element of theResource
annotation tofalse
or sets theres-sharing-scope
deployment descriptor entry for a resource manager connection factory reference toUnshareable
, the container must not attempt to share the connections obtained from the resource manager connection factory reference.[73] If the Bean Provider sets theres-sharing-scope
of a resource manager connection factory reference toShareable
or does not specifyres-sharing-scope
, the container must share the connections obtained from the resource manager connection factory according to the requirements defined in [18]. -
The container must provide tools that allow the Deployer to set up resource manager sign-on information for the resource manager references whose annotation element
authenticationType
is set toAuthenticationType.CONTAINER
or whoseres-auth
deployment descriptor element element is set toContainer
. The minimum requirement is that the Deployer must be able to specify the user/password information for each resource manager connection factory reference declared by the enterprise bean, and the container must be able to use the user/password combination for user authentication when obtaining a connection to the resource by invoking the resource manager connection factory.
Although not required by the Enterprise Beans specification, we expect that containers will support some form of a single sign-on mechanism that spans the application server and the resource managers. The container will allow the Deployer to set up the resource managers such that the Enterprise Beans caller principal can be propagated (directly or through principal mapping) to a resource manager, if required by the application.
While not required by the Enterprise Beans specification, most Enterprise Beans Container Providers also provide the following features:
-
A tool to allow the System Administrator to add, remove, and configure a resource manager for the Enterprise Beans server.
-
A mechanism to pool connections to the resources for the enterprise beans and otherwise manage the use of resources by the container. The pooling must be transparent to the enterprise beans.
10.8. Resource Environment References
This section describes the programming and
deployment descriptor interfaces that allow the Bean Provider to refer
to administered objects that are associated with resources (e.g., a
Jakarta Connectors CCI InteractionSpec
instance) by using "logical" names
called resource environment references.
Resource environment references are special entries in the enterprise
bean’s environment. The Deployer binds the resource environment
references to administered objects in the target operational
environment.
10.8.1. Bean Provider’s Responsibilities
This subsection describes the Bean Provider’s view and responsibilities with respect to resource environment references.
10.8.1.1. Injection of Resource Environment References
A field or a method of a bean may be
annotated with the Resource
annotation to request injection of a
resource environment reference. The name and type of the resource
environment reference are as described in
Annotations for Environment Entries.
The authenticationType
and shareable
elements of the Resource
annotation must not be specified; resource environment entries are not
shareable and do not require authentication. The use of the Resource
annotation to declare a resource environment reference differs from the
use of the Resource
annotation to declare simple environment
references only in that the type of a resource environment reference is
not one of the Java language types used for simple environment
references.
10.8.1.2. Resource Environment Reference Programming Interfaces
The Bean Provider must use resource environment references to locate administered objects that are associated with resources, as follows:
-
Assign an entry in the enterprise bean’s environment to the reference. (See Declaration of Resource Environment References in Deployment Descriptor for information on how resource environment references are declared in the deployment descriptor.)
-
The Enterprise Beans specification recommends, but does not require, that all resource environment references be organized in the appropriate subcontext of the bean’s environment for the resource type. Note that the resource environment references declared via annotations will not, by default, appear in any subcontext.
-
Look up the administered object in the enterprise bean’s environment using the EJBContext
lookup
method or the JNDI API.
10.8.1.3. Declaration of Resource Environment References in Deployment Descriptor
Although the
resource environment reference is an entry
in the enterprise bean’s environment, the Bean Provider must not use a
env-entry
element to declare it. Instead, the Bean Provider must declare
all references to administered objects associated with resources using
either annotations in the bean’s source code or the
resource-env-ref
elements of the deployment
descriptor. This allows the ejb-jar consumer to discover all the
resource environment references used by the enterprise bean. Deployment
descriptor entries may also be used to specify injection of a resource
environment reference into a bean.
See Section "Declaration of Resource
Environment References in Deployment Descriptor" in the
Jakarta EE Platform specification [18] for the description of the
resource-env-ref
element.
See Sharing of Environment Entries for the name scoping rules of resource environment references.
10.8.2. Deployer’s Responsibility
The Deployer is responsible for the following:
-
The Deployer must ensure that all the declared resource environment references are bound to administered objects that exist in the operational environment. The Deployer may use, for example, the JNDI
LinkRef
mechanism to create a symbolic link to the actual JNDI name of the target object. -
The Deployer must ensure that the target object is type-compatible with the type declared for the resource environment reference. This means that the target object must be of the type indicated in the
Resource
annotation or theresource-env-ref-type
element.
10.8.3. Container Provider’s Responsibility
The Container Provider must provide the
deployment tools that allow the Deployer to perform the tasks described
in the previous subsection. The deployment tools provided by the
Container Provider must be able to process the information supplied in
the class file annotations and
resource-env-ref
elements in the deployment
descriptor.
At the minimum, the tools must be able to inform the Deployer of any unresolved resource environment references, and allow him or her to resolve a resource environment reference by binding it to a specified compatible target object in the environment.
10.9. Message Destination References
This section describes the programming and deployment descriptor interfaces that allow the Bean Provider to refer to message destination objects by using "logical" names called message destination references. Message destination references are special entries in the enterprise bean’s environment. The Deployer binds the message destination references to administered message destinations in the target operational environment.
10.9.1. Bean Provider’s Responsibilities
This subsection describes the Bean Provider’s view and responsibilities with respect to message destination references.
10.9.1.1. Injection of Message Destination References
A field or a method of a bean may be
annotated with the Resource
annotation to request injection of a
message destination reference. The name and type of the resource
environment reference are as described in Annotations for Environment Entries.
The authenticationType
and shareable
elements of the Resource
annotation must not be specified.
Note that when using the Resource
annotation to declare a message destination reference it is not possible
to link the reference to other references to the same message
destination, or to specify whether the destination is used to produce or
consume messages. The deployment descriptor entries described in
Declaration of Message Destination References in Deployment Descriptor provide a way to associate multiple
message destination references with a single message destination and to
specify whether each message destination reference is used to produce,
consume, or both produce and consume messsages, so that the entire
message flow of an application may be specified. The Application
Assembler may use these message destination links to link together
message destination references that have been declared using the
Resource
annotation. A message destination reference declared via the
Resource
annotation is assumed to be used to both produce and consume
messages; this default may be overridden using a deployment descriptor
entry.
The following example illustrates how an
enterprise bean uses the Resource
annotation to request injection of a
message destination reference.
@Resource
jakarta.jms.Queue stockQueue;
10.9.1.2. Message Destination Reference Programming Interfaces
The Bean Provider uses message destination references to locate message destinations, as follows.
-
Assign an entry in the enterprise bean’s environment to the reference. (See Declaration of Message Destination References in Deployment Descriptor for information on how message destination references are declared in the deployment descriptor.)
-
The Enterprise Beans specification recommends, but does not require, that all message destination references be organized in the appropriate subcontext of the bean’s environment for the messaging resource type (e.g. in the
java:comp/env/jms
JNDI context for Jakarta Messaging Destinations). Note that message destination references declared via annotations will not, by default, appear in any subcontext. -
Look up the destination in the enterprise bean’s environment using the EJBContext
lookup
method or the JNDI APIs.
The following example illustrates how an enterprise bean uses a message destination reference to locate a Jakarta Messaging Destination.
@Resource(name="jms/StockQueue", type=jakarta.jms.Queue)
@Stateless
public class StockServiceBean implements StockService {
@Resource
SessionContext ctx;
public void processStockInfo(...) {
...
// Look up the Jakarta Messaging StockQueue in the environment.
Object result = ctx.lookup("jms/StockQueue");
// Convert the result to the proper type.
jakarta.jms.Queue queue = (jakarta.jms.Queue)result;
}
}
In the example, the Bean Provider of the
StockServiceBean
enterprise bean has assigned the environment entry
jms/StockQueue
as the message destination reference name to refer to a
Jakarta Messaging queue.
If the JNDI APIs were used directly, the example would be as follows.
@Resource(name="jms/StockQueue", type=jakarta.jms.Queue)
@Stateless
public class StockServiceBean implements StockService {
public void processStockInfo(...) {
...
// Obtain the default initial JNDI context.
Context initCtx = new InitialContext();
// Look up the Jakarta Messaging StockQueue in the environment.
Object result = initCtx.lookup(
"java:comp/env/jms/StockQueue");
// Convert the result to the proper type.
jakarta.jms.Queue queue = (jakarta.jms.Queue)result;
...
}
}
10.9.1.3. Declaration of Message Destination References in Deployment Descriptor
Although the message destination reference is
an entry in the enterprise bean’s environment, the Bean Provider must
not use a env-entry
element to declare it. Instead, the Bean Provider
should declare all references to message destinations using either the
Resource
annotation in the bean’s code or the the
message-destination-ref
elements of the deployment descriptor. This
allows the ejb-jar consumer to discover all the message destination
references used by the enterprise bean. Deployment descriptor entries
may also be used to specify injection of a message destination reference
into a bean.
Each message-destination-ref
element
describes the requirements that the referencing enterprise bean has for
the referenced destination. The message-destination-ref
element contains
optional description
, message-destination-type
, and
message-destination-usage
elements, and the mandatory
message-destination-ref-name
element.
The message-destination-ref-name
element
specifies the message destination reference name: its value is the
environment entry name used in the enterprise bean code. The name of the
message destination reference is relative to the java:comp/env
context
(e.g., the name should be jms/StockQueue
rather than
java:comp/env/jms/StockQueue
).
The message-destination-type
element
specifies the expected type of the referenced destination. For example,
in the case of a Jakarta Messaging Destination, its value might be jakarta.jms.Queue
.
The message-destination-type
element is optional if an injection
target is specified for the message destination reference; in this case
the message-destination-type
defaults to the type of the injection
target.
The message-destination-usage
element
specifies whether messages are consumed from the message destination,
produced for the destination, or both. If the
message-destination-usage
element is not specified, messages are
assumed to be both consumed and produced.
See Sharing of Environment Entries for the name scoping rules of message destination references.
The following example illustrates the declaration of message destination references in the deployment descriptor.
...
<message-destination-ref>
<description>
This is a reference to a Jakarta Messaging queue used in processing Stock info
</description>
<message-destination-ref-name>
jms/StockInfo
</message-destination-ref-name>
<message-destination-type>
jakarta.jms.Queue
</message-destination-type>
<message-destination-usage>
Produces
</message-destination-usage>
</message-destination-ref>
...
10.9.2. Application Assembler’s Responsibilities
By means of
linking message consumers and producers to one or more common logical
destinations specified in the deployment descriptor, the Application
Assembler can specify the flow of messages within an application. The
Application Assembler uses the message-destination
element, the
message-destination-link
element of the message-destination-ref
element, and the message-destination-link
element of the
message-driven
element to link message destination references to a
common logical destination.
The Application Assembler specifies the link between message consumers and producers as follows:
-
The Application Assembler uses the
message-destination
element to specify a logical message destination within the application. Themessage-destination
element defines amessage-destination-name
, which is used for the purpose of linking. -
The Application Assembler uses the
message-destination-link
element of themessage-destination-ref
element of an enterprise bean that produces messages to link it to the target destination. The value of themessage-destination-link
element is the name of the target destination, as defined in themessage-destination-name
element of themessage-destination
element. Themessage-destination
element can be in any module in the same Jakarta EE application as the referencing component. The Application Assembler uses themessage-destination-usage
element of themessage-destination-ref
element to indicate that the referencing enterprise bean produces messages to the referenced destination. -
If the consumer of messages from the common destination is a message-driven bean, the Application Assembler uses the
message-destination-link
element of themessage-driven
element to reference the logical destination. If the Application Assembler links a message-driven bean to its source destination, he or she should use themessage-destination-type
element of themessage-driven
element to specify the expected destination type. -
If an enterprise bean is otherwise a message consumer, the Application Assembler uses the
message-destination-link
element of themessage-destination-ref
element of the enterprise bean that consumes messages to link to the common destination. In the latter case, the Application Assembler uses themessage-destination-usage
element of themessage-destination-ref
element to indicate that the enterprise bean consumes messages from the referenced destination. -
To avoid the need to rename message destinations to have unique names within an entire Jakarta EE application, the Application Assembler may use the following syntax in the
message-destination-link
element of the referencing application component. The Application Assembler specifies the path name of the ejb-jar file containing the referenced message destination and appends themessage-destination-name
of the target destination separated from the path name by#
. The path name is relative to the referencing application component jar file. In this manner, multiple destinations with the samemessage-destination-name
may be uniquely identified. -
When linking message destinations, the Application Assembler must ensure that the consumers and producers for the destination require a message destination of the same or compatible type, as determined by the messaging system.
The following example illustrates the use of message destination linking in the deployment descriptor.
...
<enterprise-beans>
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<message-destination-ref>
<message-destination-ref-name>
jms/EmployeeReimbursements
</message-destination-ref-name>
<message-destination-type>
jakarta.jms.Queue
</message-destination-type>
<message-destination-usage>
Produces
</message-destination-usage>
<message-destination-link>
ExpenseProcessingQueue
</message-destination-link>
</message-destination-ref>
</session>
...
<message-driven>
<ejb-name>ExpenseProcessing</ejb-name>
<ejb-class>com.wombat.empl.ExpenseProcessingBean</ejb-class>
<messaging-type>jakarta.jms.MessageListener</messaging-type>
...
<message-destination-type>
jakarta.jms.Queue
</message-destination-type>
<message-destination-link>
ExpenseProcessingQueue
</message-destination-link>
...
</message-driven>
...
</enterprise-beans>
...
<assembly-descriptor>
...
<message-destination>
<message-destination-name>
ExpenseProcessingQueue
</message-destination-name>
</message-destination>
...
</assembly-descriptor>
The Application Assembler uses the
message-destination-link
element to indicate that the message
destination reference EmployeeReimbursement
declared in the
EmployeeService
enterprise bean is linked to the ExpenseProcessing
message-driven bean by means of the common destination
ExpenseProcessingQueue
.
The following example illustrates using the
message-destination-link
element to indicate an enterprise bean
reference to the ExpenseProcessingQueue
that is in the same Jakarta EE
application unit but in a different ejb-jar file.
<session>
...
<ejb-name>EmployeeService</ejb-name>
<ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
...
<message-destination-ref>
<message-destination-ref-name>
jms/EmployeeReimbursements
</message-destination-ref-name>
<message-destination-type>
jakarta.jms.Queue
</message-destination-type>
<message-destination-usage>
Produces
</message-destination-usage>
<message-destination-link>
finance.jar#ExpenseProcessingQueue
</message-destination-link>
</message-destination-ref>
</session>
10.9.3. Deployer’s Responsibility
The Deployer is responsible for the following:
-
The Deployer must ensure that all the declared message destination references are bound to destination objects that exist in the operational environment. The Deployer may use, for example, the JNDI
LinkRef
mechanism to create a symbolic link to the actual JNDI name of the target object. -
The Deployer must ensure that the target object is type-compatible with the type declared for the message destination reference.
-
The Deployer must observe the message destination links specified by the Application Assembler.
10.9.4. Container Provider’s Responsibility
The Container Provider must provide the
deployment tools that allow the Deployer to perform the tasks described
in the previous subsection. The deployment tools provided by the
Container Provider must be able to process the information supplied in
the message-destination-ref
and message-destination-link
elements
in the deployment descriptor.
The tools must be able to inform the Deployer of the message flow between consumers and producers sharing common message destinations. The tools must also be able to inform the Deployer of any unresolved message destination references, and allow him or her to resolve a message destination reference by binding it to a specified compatible target object in the environment.
10.10. Persistence Unit References
This section describes the metadata
annotations and deployment descriptor elements that allow the enterprise
bean code to refer to the entity manager factory for a persistence unit
using a logical name called a persistence unit reference. Persistence
unit references are special entries in the enterprise bean’s
environment. The Deployer binds the persistence unit references to
entity manager factories that are configured in accordance with the
persistence.xml
specification for the persistence unit, as described
in the Jakarta Persistence specification[3].
10.10.1. Bean Provider’s Responsibilities
This subsection describes the Bean Provider’s view of locating the entity manager factory for a persistence unit and defines his or her responsibilities. The first subsection describes annotations for injecting references to an entity manager factory for a persistence unit; the second describes the API for accessing an entity manager factory using a persistence unit reference; and the third describes syntax for declaring persistence unit references in a deployment descriptor.
10.10.1.1. Injection of Persistence Unit References
A field or a method of an enterprise bean may
be annotated with the PersistenceUnit
annotation. The name
element
specifies the name under which the entity manager factory for the
referenced persistence unit may be located in the JNDI naming context.
The optional unitName
element specifies the name of the persistence
unit as declared in the persistence.xml
file that defines the
persistence unit.
The following code example illustrates how an enterprise bean uses annotations to declare persistence unit references.
@PersistenceUnit
EntityManagerFactory emf;
@PersistenceUnit(unitName="InventoryManagement")
EntityManagerFactory inventoryEMF;
10.10.1.2. Programming Interfaces for Persistence Unit References
The Bean Provider must use persistence unit references to obtain references to entity manager factories as follows:
-
Assign an entry in the enterprise bean’s environment to the persistence unit reference. (See Declaration of Persistence Unit References in Deployment Descriptor for information on how persistence unit references are declared in the deployment descriptor.)
-
The Enterprise Beans specification recommends, but does not require, that all persistence unit references be organized in the
java:comp/env/persistence
subcontexts of the bean’s environment. -
Lookup the entity manager factory for the persistence unit in the enterprise bean’s environment using the EJBContext
lookup
method or using the JNDI API.
The following code sample illustrates
obtaining an entity manager factory when the EJBContext lookup
method
is used.
@PersistenceUnit(name="persistence/InventoryAppDB")
@Stateless
public class InventoryManagerBean implements InventoryManager {
@Resource
SessionContext ctx;
public void updateInventory(...) {
...
// use context lookup to obtain entity manager factory
EntityManagerFactory emf = (EntityManagerFactory)
ctx.lookup("persistence/InventoryAppDB");
// use factory to obtain application-managed entity manager
EntityManager em = emf.createEntityManager();
...
}
}
The following code sample illustrates obtaining an entity manager factory when the JNDI APIs are used directly.
@PersistenceUnit(name="persistence/InventoryAppDB")
@Stateless
public class InventoryManagerBean implements InventoryManager {
EJBContext ejbContext;
...
public void updateInventory(...) {
...
// obtain the initial JNDI context
Context initCtx = new InitialContext();
// perform JNDI lookup to obtain entity manager factory
EntityManagerFactory emf = (EntityManagerFactory)
initCtx.lookup("java:comp/env/persistence/InventoryAppDB");
// use factory to obtain application-managed entity manager
EntityManager em = emf.createEntityManager();
...
}
}
10.10.1.3. Declaration of Persistence Unit References in Deployment Descriptor
Although a persistence unit reference is an
entry in the enterprise bean’s environment, the Bean Provider must not
use an env-entry
element to declare it.
Instead, if metadata annotations are not
used, the Bean Provider must declare all the persistence unit references
in the deployment descriptor using the persistence-unit-ref
elements.
This allows the ejb-jar consumer (i.e. Application Assembler or
Deployer) to discover all the persistence unit references used by an
enterprise bean. Deployment descriptor entries may also be used to
specify injection of a persistence unit reference into a bean.
Each
persistence-unit-ref
element describes a single entity manager factory
reference for the persistence unit. The persistence-unit-ref
element
consists of the optional description
and persistence-unit-name
elements,
and the mandatory persistence-unit-ref-name
element.
The persistence-unit-ref-name
element
contains the name of the environment entry used in the enterprise bean’s
code. The name of the environment entry is relative to the java:comp/env
context (e.g., the name should be persistence/InventoryAppDB
rather than
java:comp/env/persistence/InventoryAppDB
). The optional
persistence-unit-name
element is the name of the persistence unit, as
specified in the persistence.xml
file for the persistence unit.
The following example is the declaration of a persistence unit reference used by the InventoryManager enterprise bean illustrated in the previous subsection.
...
<enterprise-beans>
<session>
...
<ejb-name>InventoryManagerBean</ejb-name>
<ejb-class>
com.wombat.empl.InventoryManagerBean
</ejb-class>
...
<persistence-unit-ref>
<description>
Persistence unit for the inventory management
application.
</description>
<persistence-unit-ref-name>
persistence/InventoryAppDB
</persistence-unit-ref-name>
<persistence-unit-name>
InventoryManagement
</persistence-unit-name>
</persistence-unit-ref>
...
</session>
</enterprise-beans>
...
10.10.2. Application Assembler’s Responsibilities
The Application Assembler can use the
persistence-unit-name
element in the deployment descriptor to specify
a reference to a persistence unit. The Application Assembler (or Bean
Provider) may use the following syntax in the persistence-unit-name
element of the referencing application component to avoid the need to
rename persistence units to have unique names within a Jakarta EE
application. The Application Assembler specifies the path name of the
root of the referenced persistence unit and appends the name of the
persistence unit separated from the path name by #
. The path name is
relative to the referencing application component jar file. In this
manner, multiple persistence units with the same persistence unit name
may be uniquely identified when persistence unit names cannot be
changed.
For example,
...
<enterprise-beans>
<session>
...
<ejb-name>InventoryManagerBean</ejb-name>
<ejb-class>
com.wombat.empl.InventoryManagerBean
</ejb-class>
...
<persistence-unit-ref>
<description>
Persistence unit for the inventory management
application.
</description>
<persistence-unit-ref-name>
persistence/InventoryAppDB
</persistence-unit-ref-name>
<persistence-unit-name>
../lib/inventory.jar#InventoryManagement
</persistence-unit-name>
</persistence-unit-ref>
...
</session>
</enterprise-beans>
...
The Application Assembler uses the
persistence-unit-name
element to link the persistence unit name
InventoryManagement
declared in the InventoryManagerBean
to the
persistence unit named InventoryManagement
defined in inventory.jar
.
10.10.2.1. Overriding Rules
The following rules apply to how a deployment
descriptor entry may override a PersistenceUnit
annotation:
The relevant deployment descriptor entry is located based on the JNDI name used with the annotation (either defaulted or provided explicitly).
The persistence-unit-name
overrides the
unitName
element of the annotation. The Application Assembler or
Deployer should exercise caution in changing this value, if specified,
as doing so is likely to break the application.
The injection target, if specified, must name exactly the annotated field or property method.
10.10.3. Deployer’s Responsibility
The Deployer uses deployment tools to bind a persistence unit reference to the actual entity manager factory configured for the persistence in the target operational environment.
The Deployer must perform the following tasks for each persistence unit reference declared in the metadata annotations or deployment descriptor:
-
Bind the persistence unit reference to an entity manager factory configured for the persistence unit that exists in the operational environment. The Deployer may use, for example, the JNDI
LinkRef
mechanism to create a symbolic link to the actual JNDI name of the entity manager factory. -
If the persistence unit name is specified, the Deployer should bind the persistence unit reference to the entity manager factory for the persistence unit specified as the target.
-
Provide any additional configuration information that the entity manager factory needs for managing the persistence unit, as described in [3].
10.10.4. Container Provider Responsibility
The Enterprise Beans Container Provider is responsible for the following:
-
Provide the deployment tools that allow the Deployer to perform the tasks described in the previous subsection.
-
Provide the implementation of the entity manager factory classes for the persistence units that are configured with the Enterprise Beans container. The implementation of the entity manager factory classes may be provided by the container directly or by the container in conjunction with a third-party persistence provider, as described in [3].
10.11. Persistence Context References
This section describes the metadata annotations and deployment descriptor elements that allow the enterprise bean code to refer to a container-managed entity manager of a specified persistence context type using a logical name called a persistence context reference. Persistence context references are special entries in the enterprise bean’s environment. The Deployer binds the persistence context references to container-managed entity managers for persistence contexts of the specified type and configured in accordance with their persistence unit, as described in the Jakarta Persistence specification[3].
10.11.1. Bean Provider’s Responsibilities
This subsection describes the Bean Provider’s view of locating container-managed entity managers and defines his or her responsibilities. The first subsection describes annotations for injecting references to container-managed entity managers; the second describes the API for accessing references to container-managed entity managers; and the third describes syntax for declaring these references in a deployment descriptor.
10.11.1.1. Injection of Persistence Context References
A field or a method of an enterprise bean may
be annotated with the PersistenceContext
annotation. The name
element specifies the name under which a container-managed entity
manager for the referenced persistence unit may be located in the JNDI
naming context. The optional unitName
element specifies the name of
the persistence unit as declared in the persistence.xml
file that
defines the persistence unit. The optional type
element specifies
whether a transaction-scoped or extended persistence context is to be
used. If the type is not specified, a transaction-scoped persistence
context will be used. References to container-managed entity managers
with extended persistence contexts can only be injected into stateful
session beans. The optional properties
element specifies configuration
properties to be passed to the persistence provider when the entity
manager is created.
The following code example illustrates how an enterprise bean uses annotations to declare persistence context references.
@PersistenceContext(type=EXTENDED)
EntityManager em;
10.11.1.2. Programming Interfaces for Persistence Context References
The Bean Provider must use persistence context references to obtain references to a container-managed entity manager configured for a persistence unit as follows:
-
Assign an entry in the enterprise bean’s environment to the persistence context reference. (See Declaration of Persistence Context References in Deployment Descriptor for information on how persistence context references are declared in the deployment descriptor.)
-
The Enterprise Beans specification recommends, but does not require, that all persistence context references be organized in the
java:comp/env/persistence
subcontexts of the bean’s environment. -
Lookup the container-managed entity manager for the persistence unit in the enterprise bean’s environment using the EJBContext
lookup
method or using the JNDI API.
The following code sample illustrates
obtaining an entity manager for a persistence context when the
EJBContext lookup
method is used.
@PersistenceContext(name="persistence/InventoryAppMgr")
@Stateless
public class InventoryManagerBean implements InventoryManager {
@Resource
SessionContext ctx;
public void updateInventory(...) {
...
// use context lookup to obtain container-managed entity manager
EntityManager em = (EntityManager)
ctx.lookup("persistence/InventoryAppMgr");
...
}
}
The following code sample illustrates obtaining an entity manager when the JNDI APIs are used directly.
@PersistenceContext(name="persistence/InventoryAppMgr")
@Stateless
public class InventoryManagerBean implements InventoryManager {
EJBContext ejbContext;
public void updateInventory(...) {
...
// obtain the initial JNDI context
Context initCtx = new InitialContext();
// perform JNDI lookup to obtain container-managed entity manager
EntityManager em = (EntityManager)
initCtx.lookup("java:comp/env/persistence/InventoryAppMgr");
...
}
}
10.11.1.3. Declaration of Persistence Context References in Deployment Descriptor
Although a persistence context reference is
an entry in the enterprise bean’s environment, the Bean Provider must
not use an env-entry
element to declare it.
Instead, if metadata annotations are not
used, the Bean Provider must declare all the persistence context
references in the deployment descriptor using the
persistence-context-ref
elements. This allows the ejb-jar consumer (i.e.
Application Assembler or Deployer) to discover all the persistence
context references used by an enterprise bean. Deployment descriptor
entries may also be used to specify injection of a persistence context
reference into a bean.
Each
persistence-context-ref
element describes a single container-managed
entity manager reference. The persistence-context-ref
element consists
of the optional description, persistence-unit-name
,
persistence-context-type
, persistence-context-synchronization
, and
persistence-property
elements, and the mandatory
persistence-context-ref-name
element.
The persistence-context-ref-name
element
contains the name of the environment entry used in the enterprise bean’s
code. The name of the environment entry is relative to the java:comp/env
context (e.g., the name should be persistence/InventoryAppMgr
rather
than java:comp/env/persistence/InventoryAppMgr
). The
persistence-unit-name
element is the name of the persistence unit, as
specified in the persistence.xml
file for the persistence unit. The
persistence-context-type
element specifies whether a
transaction-scoped or extended persistence context is to be used. Its
value is either Transaction
or Extended
. If the persistence context
type is not specified, a transaction-scoped persistence context will be
used. The optional persistence-context-synchronization
element specifies
whether the persistence context is automatically synchronized with the
current transaction. Its value is either Synchronized
or Unsynchronized
.
If the persistence context synchronization is not specified, the
persistence context will be automatically synchronized. The optional
persistence-property
elements specify configuration properties that
are passed to the persistence provider when the entity manager is
created.
The following example is the declaration of a
persistence context reference used by the InventoryManager
enterprise
bean illustrated in the previous subsection.
...
<enterprise-beans>
<session>
...
<ejb-name>InventoryManagerBean</ejb-name>
<ejb-class>
com.wombat.empl.InventoryManagerBean
</ejb-class>
...
<persistence-context-ref>
<description>
Persistence context for the inventory management
application.
</description>
<persistence-context-ref-name>
persistence/InventoryAppMgr
</persistence-context-ref-name>
<persistence-unit-name>
InventoryManagement
</persistence-unit-name>
</persistence-context-ref>
...
</session>
</enterprise-beans>
...
10.11.2. Application Assembler’s Responsibilities
The Application Assembler can use the
persistence-unit-name
element in the deployment descriptor to specify
a reference to a persistence unit using the syntax described in Application Assembler’s Responsibilities.
In this manner, multiple persistence units with the
same persistence unit name may be uniquely identified when persistence
unit names cannot be changed.
For example,
...
<enterprise-beans>
<session>
...
<ejb-name>InventoryManagerBean</ejb-name>
<ejb-class>
com.wombat.empl.InventoryManagerBean
</ejb-class>
...
<persistence-context-ref>
<description>
Persistence context for the inventory management
application.
</description>
<persistence-context-ref-name>
persistence/InventoryAppMgr
</persistence-context-ref-name>
<persistence-unit-name>
../lib/inventory.jar#InventoryManagement
</persistence-unit-name>
</persistence-context-ref>
...
</session>
</enterprise-beans>
...
The Application Assembler uses the
persistence-unit-name
element to link the persistence unit name
InventoryManagement
declared in the InventoryManagerBean
to the
persistence unit named InventoryManagement
defined in inventory.jar
.
10.11.2.1. Overriding Rules
The following rules apply to how a deployment
descriptor entry may override a PersistenceContext
annotation:
-
The relevant deployment descriptor entry is located based on the JNDI name used with the annotation (either defaulted or provided explicitly).
-
The
persistence-unit-name
overrides theunitName
element of the annotation. The Application Assembler or Deployer should exercise caution in changing this value, if specified, as doing so is likely to break the application. -
The
persistence-context-type
, if specified, overrides thetype
element of the annotation. In general, the Application Assembler or Deployer should never change the value of this element, as doing so is likely to break the application. -
The
persistence-context-synchronization
, if specified, overrides the synchronization element of the annotation. In general, the Application Assembler or Deployer should never change the value of this element, as doing so is likely to break the application. -
Any
persistence-property
elements are added to those specified by thePersistenceContext
annotation. If the name of a specified property is the same as one specified by thePersistenceContext
annotation, the value specified in the annotation is overridden. -
The injection target, if specified, must name exactly the annotated field or property method.
10.11.3. Deployer’s Responsibility
The Deployer uses deployment tools to bind a persistence context reference to the container-managed entity manager for the persistence context of the specified type and configured for the persistence unit in the target operational environment.
The Deployer must perform the following tasks for each persistence context reference declared in the metadata annotations or deployment descriptor:
-
Bind the persistence context reference to a container-managed entity manager for a persistence context of the specified type and configured for the persistence unit as specified in the
persistence.xml
file for the persistence unit that exists in the operational environment. The Deployer may use, for example, the JNDILinkRef
mechanism to create a symbolic link to the actual JNDI name of the entity manager. -
If the persistence unit name is specified, the Deployer should bind the persistence context reference to an entity manager for the persistence unit specified as the target.
-
Provide any additional configuration information that the entity manager factory needs for creating such an entity manager and for managing the persistence unit, as described in [3].
10.11.4. Container Provider Responsibility
The Enterprise Beans Container Provider is responsible for the following:
-
Provide the deployment tools that allow the Deployer to perform the tasks described in the previous subsection.
-
Provide the implementation of the entity manager classes for the persistence units that are configured with the Enterprise Beans container. This implementation may be provided by the container directory or by the container in conjunction with a third-party persistence provider, as described in [3].
10.12. UserTransaction Interface
The container
must make the UserTransaction interface available to the enterprise
beans that are allowed to use this interface (only session and
message-driven beans with bean-managed transaction demarcation are
allowed to use this interface) either through injection using the
Resource
annotation or in JNDI under the name
java:comp/UserTransaction
, in addition to through the EJBContext
interface. The authenticationType
and shareable
elements of the
Resource
annotation must not be specified.
The container must not make the
UserTransaction
interface available to the enterprise beans that are not
allowed to use this interface. The container should throw
javax.naming.NameNotFoundException
if an instance of an enterprise bean
that is not allowed to use the UserTransaction
interface attempts to
look up the interface in JNDI using the JNDI APIs.
The following example illustrates how an
enterprise bean acquires and uses a UserTransaction
object via
injection.
@Resource
UserTransaction tx;
...
public void updateData(...) {
...
// Start a transaction.
tx.begin();
...
// Perform transactional operations on data.
...
// Commit the transaction.
tx.commit();
...
}
The following code example
public MySessionBean implements SessionBean {
...
public someMethod() {
...
Context initCtx = new InitialContext();
UserTransaction utx = (UserTransaction)initCtx.lookup(
"java:comp/UserTransaction");
utx.begin();
...
utx.commit();
}
...
}
is functionally equivalent to
public MySessionBean implements SessionBean {
...
SessionContext ctx;
...
public someMethod() {
UserTransaction utx = ctx.getUserTransaction();
utx.begin();
...
utx.commit();
}
...
}
A UserTransaction
object reference may also
be declared in a deployment descriptor in the same way as a resource
environment reference. Such a deployment descriptor entry may be used to
specify injection of a UserTransaction
object.
10.13. ORB References
Enterprise beans that need to make use of the
CORBA ORB to perform certain operations can find an appropriate object
implementing the ORB interface by requesting injection of an ORB
object or by looking up the JNDI name java:comp/ORB
. Any such
reference to an ORB
object is only valid within the bean instance that
performed the lookup.
The following example illustrates how an
application component acquires and uses an ORB
object via injection.
@Resource
ORB orb;
public void method(...) {
...
// Get the POA to use when creating object references.
POA rootPOA = (POA)orb.resolve_initial_references("RootPOA");
...
}
The following example illustrates how an
enterprise bean acquires and uses an ORB
object using a JNDI lookup.
public void method(...) {
...
// Obtain the default initial JNDI context.
Context initCtx = new InitialContext();
// Look up the ORB object.
ORB orb = (ORB)initCtx.lookup("java:comp/ORB");
// Get the POA to use when creating object references.
POA rootPOA = (POA)orb.resolve_initial_references("RootPOA");
...
}
An ORB
reference may also be declared in a
deployment descriptor in the same way as a resource manager connection
factory reference. Such a deployment descriptor entry may be used to
specify injection of an ORB
object.
The ORB
instance available under the JNDI
name java:comp/ORB
may always be a shared instance. By default, the
ORB
instance injected into an enterprise bean or declared via a
deployment descriptor entry may also be a shared instance. However, the
application may set the shareable
element of the Resource
annotation
to false
, or may set the res-sharing-scope
element in the
deployment descriptor to Unshareable
, to request a non-shared ORB
instance.
10.13.1. Bean Provider’s Responsibility
The Bean Provider is responsible for
requesting injection of the ORB
object using the Resource
annotation, or using the defined name to look up the ORB
object. If
the shareable
element of the Resource
annotation is set to false
,
the ORB
object injected will not be the shared instance used by other
components in the application but instead will be a private ORB
instance used only by the given component.
10.14. TimerService References
The container
must make the TimerService interface available either through injection
using the Resource
annotation or in JNDI under the name
java:comp/TimerService
, in addition to through the EJBContext
interface.
The authenticationType
and shareable
elements of the Resource
annotation must not be specified.
A TimerService
object reference may also be
declared in a deployment descriptor in the same way as a resource
environment reference. Such a deployment descriptor entry may be used to
specify injection of a TimerService
object.
10.15. EJBContext References
The container
must make a component’s EJBContext
interface available either through
injection using the Resource
annotation or in JNDI under the name
java:comp/EJBContext
. The authenticationType
and shareable
elements
of the Resource
annotation must not be specified.
An EJBContext
object reference may also be
declared in a deployment descriptor in the same way as a resource
environment reference. Such a deployment descriptor entry may be used to
specify injection of an EJBContext
object.
10.15.1. Bean Provider’s Responsibility
The Bean Provider is responsible for
requesting injection of an EJBContext
object using a Resource
annotation or using the defined name to lookup the EJBContext
object.
EJBContext
objects accessed through the
naming environment are only valid within the bean instance that
performed the lookup.
10.15.2. Container Provider’s Responsibility
The Container Provider is responsible for
providing an appropriate EJBContext
object to the referencing
component. The object returned must be of the appropriate specific type
for the bean requesting injection or performing the lookup—that is, the
Container Provider must return an instance of the SessionContext
interface to referencing session beans and an instance of the
MessageDrivenContext
interface to message-driven beans.
Independent of the singleton session bean’s concurrency management type, the Container Provider must ensure concurrent access to the SessionContext object to be thread-safe.
10.16. Support for Other Resources and Configuration Parameters
The container must follow the requirements for all other resources and configuration parameters specified in the Jakarta EE Platform specification [18].
11. Security Management
This chapter defines the Enterprise Beans architecture’s support for security management.
11.1. Overview
We set the following goals for the security management in the Enterprise Beans architecture:
-
Lessen the burden of the application developer (i.e. the Bean Provider) for securing the application by allowing greater coverage from more qualified Enterprise Beans roles. The Container Provider provides the implementation of the security infrastructure; the Deployer and System Administrator define the security policies.
-
Allow the security policies to be set by the Application Assembler or Deployer.
-
Allow the enterprise bean applications to be portable across multiple Enterprise Beans servers that use different security mechanisms.
The Enterprise Beans architecture encourages the Bean Provider to implement the enterprise bean class without hard-coding the security policies and mechanisms into the business methods. In most cases, the enterprise bean’s business methods should not contain any security-related logic. This allows the Deployer to configure the security policies for the application in a way that is most appropriate for the operational environment of the enterprise.
To make the Deployer’s task easier, the Bean Provider or the Application Assembler (which could be the same party as the Bean Provider) may define security roles for an application composed of one or more enterprise beans. A security role is a semantic grouping of permissions that a given type of users of the application must have in order to successfully use the application. The Bean Provider can define declaratively using metadata annotations or the deployment descriptor the method permissions for each security role. The Applications Assembler can define, augment, or override the method permissions using the deployment descriptor. A method permission is a permission to invoke a specified group of methods of an enterprise bean’s business interface, no-interface view, home interface, component interface, and/or web service endpoint. The security roles defined by the Bean Provider or the Application Assembler present a simplified security view of the enterprise beans application to the Deployer—the Deployer’s view of the application’s security requirements is the small set of security roles rather than a large number of individual methods.
The security principal under which a method invocation is performed is typically that of the component’s caller. By specifying a run-as identity, however, it is possible to specify that a different principal be substituted for the execution of the methods of the bean’s business interface, no-interface view, home interface, component interface, and/or web service endpoint and any methods of other enterprise beans that the bean may call.
This determines whether the caller principal
is propagated from the caller to the callee—that is, whether the called
enterprise bean will see the same returned value of the
EJBContext.getCallerPrincipal
as the calling enterprise bean—or whether
a security principal that has been assigned to the specified security
role will be used for the execution of the bean’s methods and will be
visible as the caller principal in the bean’s callee.
The Bean Provider can use metadata annotations or the deployment descriptor to specify whether the caller’s security identity or a run-as security identity should be used for the execution of the bean’s methods.
-
By default, the caller principal will be propagated as the caller identity. The Bean Provider can use the
RunAs
annotation to specify that a security principal that has been assigned to a specified security role be used instead. See Specification of Security Identities in the Deployment Descriptor. -
If the deployment descriptor is used to specify the security principal, the Bean Provider or the Application Assembler can use the
security-identity
deployment descriptor element to specify the security identity. If thesecurity-identity
deployment descriptor element is not specified and if a run-as identity has not been specified by the use of theRunAs
annotation or ifuse-caller-identity
is specified as the value of thesecurity-identity
element, the caller principal is propagated from the caller to the callee. If therun-as
element is specified, a security principal that has been assigned to the specified security role will be used. The Application Assembler is permitted to override a security identity value set or defaulted by the Bean Provider.
The Deployer is responsible for assigning principals, or groups of principals, which are defined in the target operational environment, to the security roles defined by the Bean Provider or Application Assembler. The Deployer is also responsible for assigning principals for the run-as identities specified. The Deployer is further responsible for configuring other aspects of the security management of the enterprise beans, such as principal mapping for inter-enterprise bean calls, and principal mapping for resource manager access.
At runtime, a client will be allowed to invoke a business method only if the principal associated with the client call has been assigned by the Deployer to have at least one security role that is allowed to invoke the business method or if the Bean Provider or Application Assembler has specified that security authorization is not to be checked for the method (i.e., that all roles, including any unauthenticated roles, are permitted). See Method Permissions.
The Container Provider is responsible for enforcing the security policies at runtime, providing the tools for managing security at runtime, and providing the tools used by the Deployer to manage security during deployment.
Because not all security policies can be expressed declaratively, the Enterprise Beans architecture provides a simple programmatic interface that the Bean Provider may use to access the security context from the business methods.
The following sections define the responsibilities of the individual Enterprise Beans roles with respect to security management.
11.2. Bean Provider’s Responsibilities
This section defines the Bean Provider’s perspective of the Enterprise Beans architecture support for security, and defines his or her responsibilities. In addition, the Bean Provider may define the security roles for the application, as defined in Responsibilities of the Bean Provider and/or Application Assembler.
11.2.1. Invocation of Other Enterprise Beans
An enterprise bean business method can invoke another enterprise bean via the other bean’s business interface, no-interface view, or home or component interface. The Enterprise Beans architecture provides no programmatic interfaces for the invoking enterprise bean to control the principal passed to the invoked enterprise bean.
The management of caller principals passed on
inter-enterprise
bean invocations (i.e. principal delegation) is set
up by the Deployer and System Administrator in a container-specific way.
The Bean Provider and Application Assembler should describe all the
requirements for the caller’s principal management of inter-enterprise
bean invocations as part of the description.
11.2.2. Resource Access
Resource Manager Connection Factory References defines the protocol for accessing resource managers, including the requirements for security management.
11.2.3. Access of Underlying OS Resources
The Enterprise Beans architecture does not define the operating system principal under which enterprise bean methods execute. Therefore, the Bean Provider cannot rely on a specific principal for accessing the underlying OS resources, such as files. (See System Principal for the reasons behind this rule.)
We believe that most enterprise business applications store information in resource managers such as relational databases rather than in resources at the operating system levels. Therefore, this rule should not affect the portability of most enterprise beans.
11.2.4. Programming Style Recommendations
The Bean Provider should neither implement security mechanisms nor hard-code security policies in the enterprise beans’ business methods. Rather, the Bean Provider should rely on the security mechanisms provided by the Enterprise Beans container.
The Bean Provider can use metadata annotations and/or the deployment descriptor to convey security-related information to the Deployer. The information helps the Deployer to set up the appropriate security policy for the enterprise bean application.
11.2.5. Programmatic Access to Caller’s Security Context
Note: In general, security management should be enforced by the container in a manner that is transparent to the enterprise beans’ business methods. The security API described in this section should be used only in the less frequent situations in which the enterprise bean business methods need to access the security context information.
The jakarta.ejb.EJBContext
interface provides two methods that
allow the Bean Provider to access security information about the
enterprise bean’s caller.
public interface jakarta.ejb.EJBContext {
...
//
// The following two methods allow the Enterprise Beans class
// to access security information.
//
java.security.Principal getCallerPrincipal();
boolean isCallerInRole(String roleName);
}
The Bean Provider
can invoke the getCallerPrincipal
and isCallerInRole
methods only in the
enterprise bean’s business methods as specified in
Operations Allowed in the Methods of a Stateful Session Bean, Operations Allowed in the Methods of a Stateless Session Bean, Operations Allowed in the Methods of a Message-Driven Bean,
Operations Allowed in the Methods of Entity Class in Container-Managed Persistence, and
Operations Allowed in the Methods of Entity Class in Bean-Managed Persistence.
If they are otherwise invoked
when no security context exists, they should throw the
java.lang.IllegalStateException
runtime exception.
11.2.5.1. Use of getCallerPrincipal
The purpose of the getCallerPrincipal
method is to allow the enterprise bean methods to obtain the current
caller principal’s name. The methods might, for example, use the name as
a key to information in a database.
An enterprise
bean can invoke the getCallerPrincipal
method to obtain a
java.security.Principal
interface representing the current caller. The
enterprise bean can then obtain the distinguished name of the caller
principal using the getName
method of the java.security.Principal
interface. If the security identity has not been established,
getCallerPrincipal
returns the container’s representation of the
unauthenticated identity.
The meaning of the current caller, the Java
class that implements the
java.security.Principal
interface, and the
realm of the principals returned by the getCallerPrincipal
method depend
on the operational environment and the configuration of the application.
An enterprise may have a complex security
infrastructure that includes multiple security domains. The security
infrastructure may perform one or more mapping of principals on the path
from an Enterprise Beans caller to the Enterprise Beans object. For example, an employee accessing
his or her company over the Internet may be identified by a userid and
password (basic authentication), and the security infrastructure may
authenticate the principal and then map the principal to a Kerberos
principal that is used on the enterprise’s intranet before delivering
the method invocation to the Enterprise Beans object. If the security infrastructure
performs principal mapping, the getCallerPrincipal
method returns the
principal that is the result of the mapping, not the original caller
principal. (In the previous example, getCallerPrincipal
would return
the Kerberos principal.) The management of the security infrastructure,
such as principal mapping, is performed by the System Administrator
role; it is beyond the scope of the Enterprise Beans specification.
The following code sample illustrates the use
of the getCallerPrincipal()
method.
@Stateless
public class EmployeeServiceBean implements EmployeeService {
@Resource
SessionContext ctx;
@PersistenceContext
EntityManager em;
public void changePhoneNumber(...) {
...
// obtain the caller principal.
callerPrincipal = ctx.getCallerPrincipal();
// obtain the caller principal’s name.
callerKey = callerPrincipal.getName();
// use callerKey as primary key to find EmployeeRecord
EmployeeRecord myEmployeeRecord =
em.find(EmployeeRecord.class, callerKey);
// update phone number
myEmployeeRecord.setPhoneNumber(...);
...
}
}
In the previous example, the enterprise bean
obtains the principal name of the current caller and uses it as the
primary key to locate an EmployeeRecord
entity. This example assumes
that application has been deployed such that the current caller
principal contains the primary key used for the identification of
employees (e.g., employee number).
11.2.5.2. Use of isCallerInRole
The main purpose of the
isCallerInRole(String roleName)
method is to allow the Bean Provider
to code the security checks that cannot be easily defined declaratively
in the deployment descriptor using method permissions. Such a check
might impose a role-based limit on a request, or it might depend on
information stored in the database.
The enterprise
bean code can use the isCallerInRole
method to test whether the current
caller has been assigned to a given security role. Security roles are
defined by the Container, Bean Provider or the Application Assembler
(see Security Roles), and
are assigned to principals or principal groups that exist in the
operational environment by the Deployer.
The enterprise bean code can also use the
isCallerInRole
method to test whether the current caller has been
authenticated; and without further consideration of whether the
authenticated caller has been assigned to one or more specific security
roles. To perform this test, the code passes the value "**"
as the
argument to the isCallerInRole
method. As is the case with all calls to
the isCallerInRole
method, the run-time return value of the call will
depend on the security role linked to the reference (as defined in
Linking Security Role References to Security Roles) and on the principal-to-role mapping configured for
the linked role (as defined in Assignment of Security Roles).
The following code sample illustrates the use
of the isCallerInRole(String roleName)
method.
@Stateless
public class PayrollBean implements Payroll {
@Resource
SessionContext ctx;
public void updateEmployeeInfo(EmplInfo info) {
oldInfo = ... read from database;
// The salary field can be changed only by callers
// who have the security role "payroll"
if (info.salary != oldInfo.salary &&
!ctx.isCallerInRole("payroll")) {
throw new SecurityException(...);
}
...
}
...
}
11.2.5.3. Declaration of Security Roles Referenced from the Bean’s Code
The Bean Provider
is responsible for declaring all names that may be used to reference
security roles from the enterprise bean code. The names of security
roles defined in the deployment descriptor or used in the RolesAllowed
annotation are implicitly declared. The Bean Provider is responsible for
using either the DeclareRoles
annotation or the security-role-ref
elements of the deployment descriptor to declare all such names that are
not implicitly declared.
The DeclareRoles
annotation is specified on
a bean class, where it serves to declare the names of (otherwise
undeclared) roles that may be tested by calling isCallerInRole
from
within the methods of the annotated class. Declaring the security roles
allows the Bean Provider, Application Assembler, or Deployer to link
security role names used in the code to the security roles defined for
an assembled application. In the absence of this linking step, any
security role name as used in the code will be assumed to correspond to
a security role of the same name.
When the Bean Provider uses the DeclareRoles
annotation to declare the name of a role used as a parameter to the
isCallerInRole(String roleName)
method, the declared name must be the
same as the parameter value. The Bean Provider may optionally provide a
description of the named security roles in the description element of
the DeclareRoles
annotation.
In the following example, the DeclareRoles
annotation is used to indicate that the enterprise bean AardvarkPayroll
makes the security check using isCallerInRole("payroll")
in its business
method.
@DeclareRoles("payroll")
@Stateless
public class PayrollBean implements Payroll {
@Resource
SessionContext ctx;
public void updateEmployeeInfo(EmplInfo info) {
oldInfo = ... read from database;
// The salary field can be changed only by callers
// who have the security role "payroll"
if (info.salary != oldInfo.salary &&
!ctx.isCallerInRole("payroll")) {
throw new SecurityException(...);
}
...
}
...
}
The Bean Provider must use the
security-role-ref
elements of the deployment descriptor to declare any
security roles referenced in the code and not otherwise declared. The
security-role-ref
elements are defined as follows:
-
Declare the name of the security role using the
role-name
element. The name must be the security role name that is used as a parameter to theisCallerInRole(String roleName)
method. -
Optionally provide a description of the security role in the
description
element.
The following example illustrates how an enterprise bean’s references to security roles are declared in the deployment descriptor.
...
<enterprise-beans>
...
<session>
<ejb-name>AardvarkPayroll</ejb-name>
<ejb-class>com.aardvark.payroll.PayrollBean</ejb-class>
...
<security-role-ref>
<description>
This security role should be assigned to the
employees of the payroll department who are
allowed to update employees’ salaries.
</description>
<role-name>payroll</role-name>
</security-role-ref>
...
</session>
...
</enterprise-beans>
...
The deployment descriptor above indicates
that the enterprise bean AardvarkPayroll
makes the security check using
isCallerInRole("payroll")
in its business method.
A security role reference, including the name
defined by the reference, is scoped to the component whose bean class
contains the DeclareRoles
metadata annotation or whose deployment
descriptor element contains the security-role-ref
deployment descriptor
element.
The Bean Provider (or Application Assembler)
may also use the security-role-ref
elements for those references that
were declared in annotations and which the Bean Provider wishes to have
linked to a security-role
whose name differs from the reference value.
If a security role reference is not linked to a security role in this
way, the container must map the reference name to the security role of
the same name. See Linking Security Role References to Security Roles for a description of how
security role references are linked to security roles.
11.3. Responsibilities of the Bean Provider and/or Application Assembler
The Bean Provider and Application Assembler (which could be the same party as the Bean Provider) may define a security view of the enterprise beans contained in the ejb-jar file. Providing the security view is optional for the Bean Provider and Application Assembler.
The main reason for providing the security view of the enterprise beans is to simplify the Deployer’s job. In the absence of a security view of an application, the Deployer needs detailed knowledge of the application in order to deploy the application securely. For example, the Deployer would have to know what each business method does to determine which users can call it. The security view defined by the Bean Provider or Application Assembler presents a more consolidated view to the Deployer, allowing the Deployer to be less familiar with the application.
The security view consists of a set of security roles. A security role is a semantic grouping of permissions that a given type of users of an application must have in order to successfully use the application.
The Bean Provider or Application Assembler defines method permissions for each security role. A method permission is a permission to invoke a specified group of methods of the enterprise beans’ business interface, no-interface view, home interface, component interface, and/or web service endpoint.
It is important to keep in mind that the security roles are used to define the logical security view of an application. They should not be confused with the user groups, users, principals, and other concepts that exist in the target enterprise’s operational environment.
In special cases, a qualified Deployer may change the definition of the security roles for an application, or completely ignore them and secure the application using a different mechanism that is specific to the operational environment.
11.3.1. Security Roles
The Bean Provider or Application Assembler can define one or more security roles in the bean’s metadata annotations or deployment descriptor. The Bean Provider or Application Assembler then assigns groups of methods of the enterprise beans’ business, home, and component interfaces, no-interface view, and/or web service endpoints to the security roles to define the security view of the application.
Because the Bean Provider and Application Assembler do not, in general, know the security environment of the operational environment, the security roles are meant to be logical roles (or actors), each representing a type of user that should have the same access rights to the application.
The Deployer then assigns user groups and/or user accounts defined in the operational environment to the security roles defined by the Bean Provider and Application Assembler.
A security role with the name "**"
is defined
by the Container, and is intended to be used by the Bean Provider,
Application Assembler, or Deployer to indicate that the caller must log
on or authenticate to invoke a method or to perform some processing
requiring membership in this container role. This container security
role indicates that authentication, without consideration of role
membership, is required. An application role should not be defined with
the same name as this container security role, and a security role
reference should not be used to link this role reference to a different
role. Moreover the assignment of principals to the container role with
this name should not be subject to reconfiguration that would remove any
authenticated user from membership in the container role. That said,
when an application defines a security role in its deployment descriptor
with the name "**"
, this application role is applied wherever the
application or its deployment descriptor refers to a role named "**"
.
Defining the security roles in the metadata annotations and/or deployment descriptor is optional.[74] Their omission means that the Bean Provider and Application Assembler chose not to pass any security deployment related instructions to the Deployer.
If Java language metadata annotations are
used, the Bean Provider uses the DeclareRoles
and RolesAllowed
annotations to define the security roles. The set of security roles used
by the application is taken to be the aggregation of the security roles
defined by the security role names used in the DeclareRoles
and
RolesAllowed
annotations. The Bean Provider may augment the set of
security roles defined for the application by annotations in this way by
means of the security-role
deployment descriptor element.
If the deployment descriptor is used, the
Bean Provider and/or Application Assembler uses the security-role
deployment descriptor element as follows:
-
Define each security role using a
security-role
element. An application security role with name"**"
should not be defined as the Container must provide a container security role with this name. -
Use the
role-name
element to define the name of the security role. -
Optionally, use the
description
element to provide a description of a security role.
The following example illustrates security roles definition in a deployment descriptor.
...
<assembly-descriptor>
<security-role>
<description>
This role includes the employees of the
enterprise who are allowed to access the
employee self-service application. This role
is allowed only to access his/her own
information.
</description>
<role-name>employee</role-name>
</security-role>
<security-role>
<description>
This role includes the employees of the human
resources department. The role is allowed to
view and update all employee records.
</description>
<role-name>hr-department</role-name>
</security-role>
<security-role>
<description>
This role includes the employees of the payroll
department. The role is allowed to view and
update the payroll entry for any employee.
</description>
<role-name>payroll-department</role-name>
</security-role>
<security-role>
<description>
This role should be assigned to the personnel
authorized to perform administrative functions
for the employee self-service application.
This role does not have direct access to
sensitive employee and payroll information.
</description>
<role-name>admin</role-name>
</security-role>
...
</assembly-descriptor>
11.3.2. Method Permissions
If the Bean Provider and/or Application Assembler have defined security roles for the enterprise beans in the ejb-jar file, they can also specify the methods of the business, home, and component interfaces, no-interface views, and/or web service endpoints that each security role is allowed to invoke.
Metadata annotations and/or the deployment descriptor can be used for this purpose.
Method permissions are defined as a binary
relation from the set of security roles to the set of methods of the
business interfaces, home interfaces, component interfaces, no-interface
views, and/or web service endpoints of session and
entity [75] beans,
including all their
superinterfaces (including the methods of the EJBHome and EJBObject
interfaces and/or EJBLocalHome
and EJBLocalObject
interfaces). The
method permissions relation includes the pair (R, M) if and only if the
security role R is allowed to invoke the method M.
11.3.2.1. Specification of Method Permissions with Metadata Annotations
The following is the description of the rules for the specification of method permissions using Java language metadata annotations.
The method permissions for the methods of a bean class may be specified on the class, the business methods of the class, or both.
The RolesAllowed
, PermitAll
, and
DenyAll
annotations are used to specify method permissions. The value
of the RolesAllowed
annotation is a list of security role names to be
mapped to the security roles that are permitted to execute the specified
method(s). The PermitAll
annotation specifies that all security roles,
including any unauthenticated roles, are permitted to execute the
specified method(s). The DenyAll
annotation specifies that no security
roles, including any unauthenticated roles, are permitted to execute the
specified method(s).
Specifying the RolesAllowed
or PermitAll
or DenyAll
annotation on the bean class means that it applies to all
applicable business methods of the class.
Method permissions may be specified on a method of the bean class to override the method permissions value specified on the bean class.
If the bean class has superclasses, the following additional rules apply.
-
A method permissions value specified on a superclass S applies to the business methods defined by S .
-
A method permissions value may be specified on a business method M defined by class S to override for method M the method permissions value explicitly or implicitly specified on the class S.
-
If a method M of class S overrides a business method defined by a superclass of S, the method permissions value of M is determined by the above rules as applied to class S.
Example:
@RolesAllowed("admin")
public class SomeClass {
public void aMethod () {...}
public void bMethod () {...}
...
}
@Stateless
public class MyBean extends SomeClass implements A {
@RolesAllowed("HR")
public void aMethod () {...}
public void cMethod () {...}
...
}
Assuming aMethod
, bMethod
, cMethod
are methods of business interface A
, the method permissions values of
methods aMethod
and bMethod
are RolesAllowed("HR")
and
RolesAllowed("admin")
respectively. The method permissions for
method cMethod
have not been specified (see Specification of Method Permissions in the Deployment Descriptor and Unspecified Method Permissions).
11.3.2.2. Specification of Method Permissions in the Deployment Descriptor
The Bean Provider may use the deployment descriptor as an alternative to metadata annotations to specify the method permissions (or as a means to supplement or override metadata annotations for method permission values). The Application Assembler is permitted to override the method permission values using the bean’s deployment descriptor.
Any values explicitly specified in the deployment descriptor override any values specified in annotations. If a value for a method has not be specified in the deployment descriptor, and a value has been specified for that method by means of the use of annotations, the value specified in annotations will apply. The granularity of overriding is on the per-method basis.
The Bean Provider
or Application Assembler defines the method permissions relation in the
deployment descriptor using the method-permission
elements as follows.
-
Each
method-permission
element includes a list of one or more security roles and a list of one or more methods. All the listed security roles are allowed to invoke all the listed methods. Each security role in the list is identified by therole-name
element, and each method (or a set of methods, as described below) is identified by themethod
element. An optional description can be associated with amethod-permission
element using the description element. -
If the role name
"**"
is included in the list of allowed roles, and the application has not defined in its deployment descriptor an application security role with this name, then the list of allowed roles includes every and any authenticated user. -
The method permissions relation is defined as the union of all the method permissions defined in the individual
method-permission
elements. -
A security role or a method may appear in multiple
method-permission
elements.
The Bean Provider or Application Assembler
can indicate that all roles, including any unauthenticated roles, are
permitted to execute one or more specified methods (i.e., the methods
should not be “checked” for authorization prior to invocation by the
container). The unchecked
element is used instead of a role name in
the method-permission
element to indicate that all roles, including
any unauthenticated roles, are permitted.
If the method permission relation specifies
both the unchecked
element for a given method and one or more security
roles, all roles are permitted for the specified methods.
The exclude-list
element can be used to indicate the set of
methods that should not be called. The Deployer should configure the
enterprise bean’s security such that no access is permitted to any
method contained in the exclude-list
.
If a given method is specified both in the
exclude-list
element and in the method permission relation, the
Deployer should configure the enterprise bean’s security such that no
access is permitted to the method.
The method
element uses the ejb-name
, method-name
, and method-params
elements to
denote one or more methods of an enterprise bean’s business interface,
home interface, component interface, no-interface view, and/or web
service endpoint. There are three legal styles for composing the method
element:
Style 1:
<method>
<ejb-name>EJBNAME</ejb-name>
<method-name>*</method-name>
</method>
This style is used for referring to all of the methods of the business, home, and component interfaces, no-interface view, and web service endpoint of a specified enterprise bean.
Style 2:
<method>
<ejb-name>EJBNAME</ejb-name>
<method-name>METHOD</method-name>
</method>
This style is used for referring to a specified method of the business, home, or component interface, no-interface view, or web service endpoint of the specified enterprise bean. If there are multiple methods with the same overloaded name, this style refers to all of the overloaded methods.
Style 3:
<method>
<ejb-name>EJBNAME</ejb-name>
<method-name>METHOD</method-name>
<method-params>
<method-param>PARAMETER_1</method-param>
...
<method-param>PARAMETER_N</method-param>
</method-params>
</method>
This style is used to refer to a specified method within a set of methods with an overloaded name. The method must be defined in the specified enterprise bean’s business, home, or component interface, no-interface view, or web service endpoint. If there are multiple methods with the same overloaded name, however, this style refers to all of the overloaded methods.
The optional method-intf
element can be
used to differentiate between methods with the same name and signature
that are multiply defined across the business, component, or home
interfaces, no-interface view, and/or web service endpoint. If the same
method is a method of a local business interface, local component
interface, or no-interface view, the same method permission values apply
to the method for all of them. Likewise, if the same method is a method
of both the remote business interface and remote component interface,
the same method permission values apply to the method for both
interfaces.
The following example illustrates how security roles are assigned method permissions in the deployment descriptor:
...
<method-permission>
<role-name>employee</role-name>
<method>
<ejb-name>EmployeeService</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
<method-permission>
<role-name>employee</role-name>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>findByPrimaryKey</method-name>
</method>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>getEmployeeInfo</method-name>
</method>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>updateEmployeeInfo</method-name>
</method>
</method-permission>
<method-permission>
<role-name>payroll-department</role-name>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>findByPrimaryKey</method-name>
</method>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>getEmployeeInfo</method-name>
</method>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>updateEmployeeInfo</method-name>
</method>
<method>
<ejb-name>AardvarkPayroll</ejb-name>
<method-name>updateSalary</method-name>
</method>
</method-permission>
<method-permission>
<role-name>admin</role-name>
<method>
<ejb-name>EmployeeServiceAdmin</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
...
11.3.2.3. Unspecified Method Permissions
It is possible that some methods are not
assigned to any security roles nor annotated as DenyAll
or contained
in the exclude-list
element. In this case, the Deployer should assign
method permissions for all of the unspecified methods, either by
assigning them to security roles, or by marking them as unchecked
. If
the Deployer does not assigned method permissions to the unspecified
methods, those methods must be treated by the container as unchecked
.
11.3.3. Linking Security Role References to Security Roles
The application’s references to security
roles are linked to the security roles defined for the application. In
the absence of any explicit linking, a security role reference will be
linked to a security role having the same name. This requirement also
applies to role references with value "**"
, and an explicit mapping
should only be defined for a role reference with value "**"
when the
reference needs to be linked to an application role with name other than
"**"
.
The Application Assembler uses a
security-role-ref
element to explicitly link a role reference by a
component to a security role defined by annotation and/or by
security-role
element (as described in Security Roles). The linkage is made
explicit using the role-link
element of the security-role-ref
element;
in which case the value of the role-link
element must be the name of one
of the security roles defined by annotation and/or security-role
element.
A security-role-ref
element need not be
defined for a role reference that is to be mapped to a security-role
with the same name as the role reference, and when a role-link
is not
specified within a security-role-ref
, the reference is implicitly mapped
to the security role with the same name as the reference.
The following deployment descriptor example
shows how to link the security role reference named payroll
to the
security role named payroll-department
.
...
<enterprise-beans>
...
<session>
<ejb-name>AardvarkPayroll</ejb-name>
<ejb-class>com.aardvark.payroll.PayrollBean</ejb-class>
...
<security-role-ref>
<description>
This role should be assigned to the
employees of the payroll department.
Members of this role have access to
anyone’s payroll record.
The role has been linked to the
payroll-department role.
</description>
<role-name>payroll</role-name>
<role-link>payroll-department</role-link>
</security-role-ref>
...
</session>
...
</enterprise-beans>
...
11.3.4. Specification of Security Identities in the Deployment Descriptor
The Bean Provider or Application Assembler typically specifies whether the caller’s security identity should be used for the execution of the methods of an enterprise bean or whether a specific run-as identity should be used.
By default the caller’s security identity is
used. The Bean Provider can use the RunAs
metadata annotation to
specify a run-as identity for the execution of the bean’s methods. If
the deployment descriptor is used, the Bean Provider or the Application
Assembler can use the security-identity
deployment descriptor element
for this purpose or to override a security identity specified in
metadata. The value of the security-identity
element is either
use-caller-identity
or run-as
.
Defining the security identities in the deployment descriptor is optional for the Application Assembler. Their omission in the deployment descriptor means that the Application Assembler chose not to pass any instructions related to security identities to the Deployer in the deployment descriptor.
If a run-as security identity is not specified by the Deployer, the container should use the caller’s security identity for the execution of the bean’s methods.
11.3.4.1. Run-as
The Bean Provider can use the RunAs
metadata annotation or the Bean Provider or Application Assembler can
use the run-as
deployment descriptor
element to define a run-as identity for an enterprise bean in the
deployment descriptor. The run-as identity applies to the enterprise
bean as a whole, that is, to all methods of the enterprise bean’s
business, home, and component interfaces, no-interface view, and/or web
service endpoint; to the message listener methods of a message-driven
bean; and to the timeout callback methods of an enterprise bean; and all
internal methods of the bean that they might in turn call.
Establishing a run-as identity for an enterprise bean does not affect the identities of its callers, which are the identities tested for permission to access the methods of the enterprise bean. The run-as identity establishes the identity the enterprise bean will use when it makes calls.
Because the Bean Provider and Application Assembler do not, in general, know the security environment of the operational environment, the run-as identity is designated by a logical role-name, which corresponds to one of the security roles defined by the Bean Provider or Application Assembler in the metadata annotations or deployment descriptor.
The Deployer then assigns a security
principal defined in the operational environment to be used as the
principal for the run-as identity. The security principal assigned by
the Deployer should be a principal that has been assigned to the
security role specified by RunAs
annotation or by the role-name
element of the run-as
deployment
descriptor element.
The Bean Provider and/or Application Assembler is responsible for the following in the specification of run-as identities:
-
Use the
RunAs
metadata annotation orrole-name
element of therun-as
deployment descriptor element to define the name of the security role. -
Optionally, use the
description
element to provide a description of the principal that is expected to be bound to the run-as identity in terms of its security role.
The following example illustrates the definition of a run-as identity using metadata annotations.
@RunAs("admin")
@Stateless
public class EmployeeServiceBean implements EmployeeService {
...
}
Using the deployment descriptor, this can be specified as follows.
...
<enterprise-beans>
...
<session>
<ejb-name>EmployeeService</ejb-name>
...
<security-identity>
<run-as>
<role-name>admin</role-name>
</run-as>
</security-identity>
...
</session>
...
</enterprise-beans>
...
11.4. Deployer’s Responsibilities
The Deployer is responsible for ensuring that an assembled application is secure after it has been deployed in the target operational environment. This section defines the Deployer’s responsibility with respect to Enterprise Beans security management.
The Deployer uses deployment tools provided by the Container Provider to read the security view of the application supplied by the Bean Provider and/or Application Assembler in the metadata annotations and/or deployment descriptor. The Deployer’s job is to map the security view that was specified by the Bean Provider and/or Application Assembler to the mechanisms and policies used by the security domain in the target operational environment. The output of the Deployer’s work includes an application security policy descriptor that is specific to the operational environment. The format of this descriptor and the information stored in the descriptor are specific to the Enterprise Beans container.
The following subsections describe the security related tasks performed by the Deployer.
11.4.1. Security Domain and Principal Realm Assignment
The Deployer is responsible for assigning the security domain and principal realm to an enterprise bean application.
Multiple principal realms within the same security domain may exist, for example, to separate the realms of employees, trading partners, and customers. Multiple security domains may exist, for example, in application hosting scenarios.
11.4.2. Assignment of Security Roles
The Deployer assigns principals and/or groups
of principals (such as individual users or user groups) used for
managing security in the operational environment to the security roles
defined by means of the DeclareRoles
and RolesAllowed
metadata
annotations and/or security-role
elements of the deployment descriptor.
The Deployer does not define (or in effect
redefine) the principals assigned to the container security role with
name "**"
. The Container is required to assign a principal of any and
every authenticated user (as defined by the operational environment of
the application) to the container security role with this name.
The Deployer does not assign principals
and/or principal groups to the security role references—the principals
and/or principals groups assigned to a security role apply also to all
the linked security role references. For example, the Deployer of the
AardvarkPayroll
enterprise bean in Linking Security Role References to Security Roles
would assign principals and/or principal groups to the
security-role payroll-department
, and the assigned principals and/or
principal groups would be implicitly assigned also to the linked
security role reference payroll
.
The Enterprise Beans architecture does not specify how an enterprise should implement its security architecture. Therefore, the process of assigning the logical security roles defined in the application’s deployment descriptor to the operational environment’s security concepts is specific to that operational environment. Typically, the deployment process consists of assigning to each security role one or more user groups (or individual users) defined in the operational environment. This assignment is done on a per-application basis. (That is, if multiple independent ejb-jar files use the same security role name, each may be assigned differently.) If the Deployer does not assign the logical security roles defined by the application to groups in the operational environment, it must be assumed that a logical role maps to a principal or principal group of the same name.
11.4.3. Principal Delegation
The Deployer is
responsible for configuring the principal delegation for inter-component
calls. The Deployer must follow any instructions supplied by the Bean
Provider and/or Application Assembler (for example, provided in the
RunAs
metadata annotations, the run-as
elements of the deployment descriptor, in the description elements of
the annotations or deployment descriptor, or in a deployment manual).
If the security identity is defaulted, or it
is explicitly specified that the caller identity be used (e.g.,
use-caller-identity
deployment descriptor
element is specified), the caller principal is propagated from one
component to another (i.e., the caller principal of the first enterprise
bean in a call-chain is passed to the enterprise beans down the chain).
If the Bean Provider or Application Assembler specifies that a run-as identity be used on behalf of a particular enterprise bean, the Deployer must configure the enterprise beans such that the run-as principal is used as the caller principal on any calls that the enterprise bean makes to other beans, and that the run-as principal is propagated along the call-chain of those other beans (in the absence of the specification of any further run-as elements).
11.4.4. Security Management of Resource Access
The Deployer’s responsibilities with respect to securing resource managers access are defined in Deployer’s Responsibility.
11.4.5. General Notes on Deployment Descriptor Processing
The Deployer can use the security view defined in the deployment descriptor by the Bean Provider and Application Assembler merely as "hints" and may change the information whenever necessary to adapt the security policy to the operational environment.
Since providing the security information is optional for the Bean Provider and Application Assembler, the Deployer is responsible for performing any tasks that have not been done by the Bean Provider or Application Assembler. (For example, if the definition of security roles and method permissions is missing in the metadata annotations and in deployment descriptor, the Deployer must define the security roles and method permissions for the application.) It is not required that the Deployer store the output of this activity in the standard ejb-jar file format.
11.5. Enterprise Beans Client Responsibilities
This section defines the rules that the Enterprise Beans client program must follow to ensure that the security context passed on the client calls, and possibly imported by the enterprise bean, do not conflict with the Enterprise Beans server’s capabilities for association between a security context and transactions.
These rules are:
-
A transactional client cannot change its principal association within a transaction. This rule ensures that all calls from the client within a transaction are performed with the same security context.
-
A session bean’s client must not change its principal association for the duration of the communication with the session object. This rule ensures that the server can associate a security identity with the session instance at instance creation time, and never have to change the security association during the session instance lifetime.
-
If transactional requests within a single transaction arrive from multiple clients (this could happen if there are intermediary objects or programs in the transaction call-chain), all requests within the same transaction must be associated with the same security context.
11.6. Container Provider’s Responsibilities
This section describes the responsibilities of the Container Provider and Server Provider.
11.6.1. Deployment Tools
The Container Provider is responsible for providing the deployment tools that the Deployer can use to perform the tasks defined in Deployer’s Responsibilities.
The deployment tools read the information from the beans’ metadata annotations and/or deployment descriptor and present the information to the Deployer. The tools guide the Deployer through the deployment process, and present him or her with choices for mapping the security information in the metadata annotations and deployment descriptor to the security management mechanisms and policies used in the target operational environment.
The deployment tools’ output is stored in an Enterprise Beans container-specific manner, and is available at runtime to the Enterprise Beans container.
11.6.2. Security Domain(s)
The Enterprise Beans container provides a security domain and one or more principal realms to the enterprise beans. The Enterprise Beans architecture does not specify how an Enterprise Beans server should implement a security domain, and does not define the scope of a security domain.
A security domain can be implemented, managed, and administered by the Enterprise Beans server. For example, the Enterprise Beans server may store X509 certificates or it might use an external security provider such as Kerberos.
The Enterprise Beans specification does not define the scope of the security domain. For example, the scope may be defined by the boundaries of the application, Enterprise Beans server, operating system, network, or enterprise.
The Enterprise Beans server can, but is not required to, provide support for multiple security domains, and/or multiple principal realms.
The case of multiple domains on the same Enterprise Beans server can happen when a large server is used for application hosting. Each hosted application can have its own security domain to ensure security and management isolation between applications owned by multiple organizations.
11.6.3. Security Mechanisms
The Container Provider must provide the security mechanisms necessary to enforce the security policies set by the Deployer. The Enterprise Beans specification does not specify the exact mechanisms that must be implemented and supported by the Enterprise Beans server.
The typical security functions provided by the Enterprise Beans server include:
-
Authentication of principals.
-
Access authorization for Enterprise Beans calls and resource manager access.
-
Secure communication with remote clients (privacy, integrity, etc.).
11.6.4. Passing Principals on Enterprise Beans Calls
The Container Provider is responsible for providing the deployment tools that allow the Deployer to configure the principal delegation for calls from one enterprise bean to another. The Enterprise Beans container is responsible for performing the principal delegation as specified by the Deployer.
The Enterprise Beans container
must be capable of allowing the Deployer to specify that, for all calls
from a single application within a single Jakarta EE product, the caller
principal is propagated on calls from one enterprise bean to another
(i.e., the multiple beans in the call chain will see the same return
value from getCallerPrincipal
).
This requirement is necessary for
applications that need a consistent return value of getCallerPrincipal
across a chain of calls between enterprise beans.
The Enterprise Beans container must be capable of allowing the Deployer to specify that a run-as principal be used for the execution of the business, home, and component interfaces, no-interface view, and/or web service endpoint methods of a session or an entity [76] bean, or for the message listener methods of a message-driven bean.
11.6.5. Security Methods in jakarta.ejb.EJBContext
The Enterprise Beans container
must provide access to the caller’s security context information from
the enterprise beans’ instances via the getCallerPrincipal()
and
isCallerInRole(String roleName)
methods. The Enterprise Beans container must provide
the caller’s security context information during the execution of a
business method invoked via the enterprise bean’s business, home,
component, no-interface view, or messsage listener interface, web
service endpoint, and/or TimedObject
interface, as defined in
Operations Allowed in the Methods of a Stateful Session Bean, Operations Allowed in the Methods of a Stateless Session Bean,Operations Allowed in the Methods of a Message-Driven Bean, Operations Allowed in the Methods of Entity Class in Container-Managed Persistence, and
Operations Allowed in the Methods of Entity Class in Bean-Managed Persistence.
The container must ensure that
all enterprise bean method invocations received through these interfaces
are associated with some principal. If the security identity of the
caller has not been established, the container returns the container’s
representation of the unauthenticated identity. The container must never
return a null
from the getCallerPrincipal
method.
11.6.6. Secure Access to Resource Managers
The Container Provider is responsible for providing secure access to resource managers as described in Container Provider Responsibility.
11.6.7. Principal Mapping
If the application requires that its clients are deployed in a different security domain, or if multiple applications deployed across multiple security domains need to interoperate, the Container Provider is responsible for the mechanism and tools that allow mapping of principals. The tools are used by the System Administrator to configure the security for the application’s environment.
11.6.8. System Principal
The Enterprise Beans specification does not define the "system" principal under which the JVM running an enterprise bean’s method executes.
Leaving the principal undefined makes it easier for the Enterprise Beans container vendors to provide runtime support for Enterprise Beans on top of their existing server infrastructures. For example, while one Enterprise Beans container implementation can execute all instances of all enterprise beans in a single JVM, another implementation can use a separate JVM per ejb-jar per client. Some Enterprise Beans containers may make the system principal the same as the application-level principal. Others may use different principals, potentially from different principal realms and even security domains.
11.6.9. Runtime Security Enforcement
The Enterprise Beans container is responsible for enforcing the security policies defined by the Deployer. The implementation of the enforcement mechanism is Enterprise Beans container implementation-specific. The Enterprise Beans container may, but does not have to, use the Java programming language security as the enforcement mechanism.
For example, to isolate multiple executing enterprise bean instances, the Enterprise Beans container can load the multiple instances into the same JVM and isolate them via using multiple class loaders, or it can load each instance into its own JVM and rely on the address space protection provided by the operating system.
The general security enforcement requirements for the Enterprise Beans container follow:
-
The Enterprise Beans container must provide enforcement of the client access control per the policy defined by the Deployer. A caller is allowed to invoke a method if, and only if, the method is specified as
PermitAll
or the caller is assigned at least one of the security roles that includes the method in its method permissions definition. (That is, it is not meant that the caller must be assigned all the roles associated with the method.) If the container denies a client access to a business method, the container should throw thejakarta.ejb.EJBAccessException
.[77] If the Enterprise Beans 2.1 client view is used, the container must throw thejava.rmi.RemoteException
(or its subclass, thejava.rmi.AccessException
) to the client if the client is a remote client, or thejakarta.ejb.EJBException
(or its subclass, thejakarta.ejb.AccessLocalException
) if the client is a local client. -
The Enterprise Beans container must isolate an enterprise bean instance from other instances and other application components running on the server. The Enterprise Beans container must ensure that other enterprise bean instances and other application components are allowed to access an enterprise bean only via the enterprise bean’s business interface, component interface, home interface, no-interface view, and/or web service endpoint.
-
The Enterprise Beans container must isolate an enterprise bean instance at runtime such that the instance does not gain unauthorized access to privileged system information. Such information includes the internal implementation classes of the container, the various runtime state and context maintained by the container, object references of other enterprise bean instances, or resource managers used by other enterprise bean instances. The Enterprise Beans container must ensure that the interactions between the enterprise beans and the container are only through the Enterprise Beans architected views.
-
The Enterprise Beans container must ensure the security of the persistent state of the enterprise beans.
-
The Enterprise Beans container must manage the mapping of principals on calls to other enterprise beans or on access to resource managers according to the security policy defined by the Deployer.
-
The container must allow the same enterprise bean to be deployed independently multiple times, each time with a different security policy.[78] The container must allow multiple-deployed enterprise beans to co-exist at runtime.
11.6.10. Audit Trail
The Enterprise Beans container
may provide a security audit trail mechanism. A security audit trail
mechanism typically logs all java.security
Exceptions. It also logs
all denials of access to Enterprise Beans servers, Enterprise Beans containers, Enterprise Beans business
interfaces, Enterprise Beans component interfaces, Enterprise Beans home interfaces, Enterprise Beans
no-interface views, and Enterprise Beans web service endpoints.
11.7. System Administrator’s Responsibilities
This section defines the security-related responsibilities of the System Administrator. Note that some responsibilities may be carried out by the Deployer instead, or may require cooperation of the Deployer and the System Administrator.
11.7.1. Security Domain Administration
The System Administrator is responsible for the administration of principals. Security domain administration is beyond the scope of the Enterprise Beans specification.
Typically, the System Administrator is responsible for creating a new user account, adding a user to a user group, removing a user from a user group, and removing or freezing a user account.
11.7.2. Principal Mapping
If the client is in a different security domain than the target enterprise bean, the System Administrator is responsible for mapping the principals used by the client to the principals defined for the enterprise bean. The result of the mapping is available to the Deployer.
The specification of principal mapping techniques is beyond the scope of the Enterprise Beans architecture.
12. Timer Service
This chapter defines the Enterprise Beans container-managed Timer Service. The Enterprise Beans Timer Service is a container-provided service that allows the Bean Provider to register enterprise beans for timer callbacks to occur according to a calendar-based schedule, at a specified time, after a specified elapsed time, or at specified intervals.
12.1. Overview
Enterprise applications that model workflow-type business processes are dependent on notifications that certain temporal events have occurred in order to manage the semantic state transitions that are intrinsic to the business processes that they model.
The Enterprise Beans Timer Service is a container-managed service that allows callbacks to be scheduled for time-based events. The container provides a reliable and transactional notification service for timed events. Timer notifications may be scheduled to occur according to a calendar-based schedule, at a specific time, after a specific elapsed duration, or at specific recurring intervals.
The Timer Service is implemented by the Enterprise Beans
container. An enterprise bean accesses this service by means of
dependency injection, through the EJBContext
interface, or through
lookup in the JNDI namespace.
The Enterprise Beans Timer Service is a coarse-grained timer notification service that is designed for use in the modeling of application-level processes. It is not intended for the modeling of real-time events.
The following sections describe the Timer Service with respect to the various individual Enterprise Beans roles.
12.2. Bean Provider’s View of the Timer Service
The Enterprise Beans Timer Service is a container-provided service that allows enterprise beans to be registered for timer callback methods to occur according to a calendar-based schedule, at a specified time, after a specified elapsed time, or after specified intervals. The Timer Service provides methods for the programmatic creation and cancellation of timers, as well as for locating the timers that are associated with a bean or with all beans in an Enterprise Beans module. Timers can also be created automatically by the container at deployment time based on metadata in the bean class or in the deployment descriptor.
A timer is created to schedule timed callbacks. The bean class of an enterprise bean that uses the Timer Service can provide one or more timeout callback methods. A bean can have one or more callback methods corresponding to automatically-created timers as well as a callback method corresponding to one or more programmatically-created timers.
For programmatically created timers, the
timeout callback method must either be a single method that is annotated
with the Timeout
annotation or the bean must implement the
jakarta.ejb.TimedObject
interface. The jakarta.ejb.TimedObject
interface
has a single method, the timer callback method ejbTimeout
.
For automatically created timers, the Schedule annotation denotes its the timeout method.
Timers can be created for stateless session beans, singleton session beans, message-driven beans.[79] Timers cannot be created for stateful session beans.[80]
The timeout callback method invocation for a timer that is created for a stateless session bean or a message-driven bean may be called on any bean instance in the pooled state.
The timeout callback method for a programmatically created persistent timer will be invoked on the JVM on which the timer was created or on another JVM instance across which the container is distributed. The timeout callback method for a programmatically created non-persistent timer will be invoked on the JVM on which the timer was created. The timeout callback method for a programmatically created timer is invoked on a single JVM instance regardless of the number of JVMs across which the container is distributed.
For each automatically-created persistent timer, the container creates a single persistent timer, regardless of the number of JVMs across which the container is distributed. For automatically-created non-persistent timers, the container creates a new non-persistent timer during application initialization for each JVM across which the container is distributed.
In the event of a container crash or container shutdown, the timeout callback method for a persistent timer that has not been cancelled will be invoked on a new JVM when the container is restarted or on another JVM instance across which the container is distributed. This rule applies to both programmatically or automatically created persistent timers.
When the time specified at timer creation
elapses, the container invokes the associated timeout callback method of
the bean. A timer may be cancelled before its expiration. If a timer is
cancelled, its associated timeout callback method is not
called.[81] A timer is cancelled by calling its
cancel
method.
Invocations of the timeout callback methods and the methods of the Timer Service to programmatically create timers and to cancel timers are typically made within a transaction.
The Timer Service is intended for the modelling of long-lived business processes. Timers survive container crashes, server shutdown, and the activation/passivation and load/store cycles of the enterprise beans that are registered with them. These persistent guarantees can optionally be disabled on a per-timer basis.
12.2.1. Calendar-Based Time Expressions
The Timer Service allows a timer callback schedule to be expressed using a calendar-based syntax that is modeled after the UNIX cron facility. Calendar-based expressions can be used both for programmatic timer creation and for automatic timer creation, and can be specified by means of annotations or the deployment descriptor. Each of these approaches for expressing the calendar-based schedule shares common syntax and defaults.
12.2.1.1. Calendar-Based Time Expression Attributes
There are seven attributes in a calendar-based time expression:
-
second: one or more seconds within a minute
Allowable values: [0,59] -
minute: one or more minutes within an hour
Allowable values: [0,59] -
hour: one or more hours within a day
Allowable values: [0,23] -
dayOfMonth: one or more days within a month
Allowable values:-
[1,31] or
-
[-7, -1] or
-
"Last" or
-
{"1st", "2nd", "3rd", "4th", "5th", "Last"}
-
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
"Last" means the last day of the month
-x (where x is in the range [-7, -1]) means x day(s) before the last day of the month
"1st","2nd", etc. applied to a day of the week identifies a single occurrence of that day within the month. -
-
month: one or more months within a year
Allowable values:-
[1,12] or
-
{"Jan", "Feb", "Mar", ‘’Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", Dec"}
-
-
dayOfWeek: one or more days within a week
Allowable values:-
[0,7] or
-
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
"0" and "7" both refer to Sunday
-
-
year: a particular calendar year
Allowable values: a four-digit calendar year
12.2.1.2. Attribute Syntax
Each attribute supports values expressed in one of the following forms:
Single Value
Use of a single value constrains the attribute to only one of its possible values.
Examples:
second = "10"
month= "Sep"
Wild Card
The wild card "*"
represents all possible
values for a given attribute.
Examples:
second = "*"
dayOfWeek = "*"
List
A list constrains the attribute to two or more allowable values or ranges, with a comma used as a separator character and a dash used to indicate an inclusive range. Each item in the list must be an individual attribute value or a range. List items cannot themselves be lists, wild-cards, or increments. Duplicate values are allowed, but are ignored.
Examples:
second = "10,20,30"
dayOfWeek = "Mon,Wed,Fri"
minute = "0-10,30,40"