KEMBAR78
Introduction to EJB | PPTX
Core Systems Transformation Solutions
Enterprise Java Beans Overview. Part 1
October 15, 2015
Confidential 1
Agenda
1. Overview
2. Session Beans
3. Accessing Session Beans
4. Messaging and MDB
5. References and Injections
6. Transactions
7. Exception Handling
Confidential 2
Overview
Confidential 3
What is EJB ?
Enterprise Java Beans
• is platform for building portable, reusable, and scalable
business applications using the Java
• is Java components (classes) that executes in a specialized
runtime environment called the EJB container
Confidential 4
Java EE Components
Confidential 5
EJB container functionality
5
Resources
Client
ClientSupport
Lifecycle Management
Resource Management
EJB EJB EJB
Confidential 6
EJB Container Services
EJB Container provides valuable services for enterprise
application development:
• Transactions support
• Security model
• Persistence support
• Remote access
• Web-services
• Interceptors
• Thread Safety and Concurrency control
• Timing services & job scheduling
• Messaging
• Asynchronous interactions
Confidential 7
EJB Version History
 EJB 1.1 (J2EE 1.2), 1999
– Session beans (stateful & stateless), Entity Beans
– Remote interface
 EJB 2.0 (J2EE 1.3), 2001
– Message Driven beans
– Entity 2.x and EJB QL
– Local & Remote Interfaces
 EJB 2.1 (J2EE 1.4), 2003
– EJB Timer Service
– EJB QL updates
 EJB 3 (2006) , 3.1(2009), 3.2 (2013)
Confidential 8
Types of Enterprise Bean Objects
• Session Beans
• Message-driven beans
• Entities
Confidential 9
Session Beans
Confidential 10
Session Beans
• Performs specific business-logic operations
• Managed by EJB Container
• Available for a client session
• Is removed when the EJB container crashes
• Can be transaction-aware
• Can be invoked either locally or remotely using Java RMI
Confidential 11
Session Beans
Session bean object is not directly accessed
Session EJB component has the following elements:
• Component interface
• Implementation class
Confidential 12
Types of Session Beans
• Stateless Session Beans
• Stateful Session Beans
• Singleton Session Beans
Confidential 13
Stateless Session Bean
• Does not retain client-specific information
• A client might not get the same session bean instance
• Can implement a web service
• Any number of requests can be handled by the same instance
Confidential 14
Stateless Session Bean
EJB
EJB
EJB
EJB
EJB
Request
Instance Pool
EJB Container
Random
Selection
Confidential 15
Stateless Bean Lifecycle and Callbacks
@Stateless
public class CalculationBean {
@PostConstruct
void construct() {
}
@PreDestroy
void destroy() {
}
public int sum(int a, int b) {
return a + b;
}
}
Confidential 16
Stateless Session Bean Example
@Local
public interface CalculationLocal {
int sum(int a, int b);
}
@Stateless
public class CalculationBean implements CalculationLocal {
public int sum(int a, int b) {
return a + b;
}
}
Confidential 17
Stateful Session Bean
• Supports conversation state
• Is never shared, has only one client
• Client can remove bean instance
• Can be passivated by container
• Cannot implement a web service
Confidential 18
Stateful Session Bean
EJB
id = 3
EJB
id = 4
EJB
id = 5
EJB
id = 1
EJB
id = 2
Request
Instance Cache
EJB Container
Select by
Session ID
ID = 5
Confidential 19
Stateful Bean Lifecycle and Callbacks
Confidential 20
Stateful Bean Lifecycle and Callbacks (Example)
@Stateful
public class CalculationBean implements CalculationRemote {
private int result = 0;
@PostConstruct
void construct(){}
@PreDestroy
void destroy(){}
@PostActivate
void activate(){}
@PrePassivate
void passivate(){}
@Remove
public void remove(){}
public void add(int a) {
result += a;
}
public int getResult() {
return result;
}
}
Confidential 21
Singleton Session Bean
• Instantiated once per application and exists for the lifecycle
of the application
• Only one bean per application (jvm)
• Does not maintain state across server crashes/shutdowns
• Supports concurrency requests
• Can implement a web service
• Perform tasks upon application startup and shutdown
• State shared across the application
Confidential 22
Singleton Session Bean. Concurrency Management
Singleton session beans are designed for concurrent access
@javax.ejb.ConcurrencyManagement :
- container-managed concurrency
javax.ejb.ConcurrencyManagementType.CONTAINER -
default
- bean-managed concurrency
javax.ejb.ConcurrencyManagementType.BEAN
Confidential 23
Container-Managed concurrency. Locking types
Access locking types:
javax.ejb.Lock,
javax.ejb.LockType
- @Lock(LockType.READ) - for read-only operations
- @Lock(LockType.WRITE) - default; for exclusive access to the
bean instance
javax.ejb.AccessTimeout - annotation is used to specify the
number of TimeUnits before an access timeout occurs
Confidential 24
Container-Managed Singleton Example
@Singleton
@ConcurrencyManagement(CONTAINER)
@AccessTimeout(value=20, unit = TimeUnit.SECONDS)
public class CalculationBean implements CalculationLocal {
private Long result;
@PostConstruct
void construct() {
result = 0L;
}
@Lock(LockType.WRITE)
public void add(int a) {
result += a;
}
@Lock(LockType.READ)
@AccessTimeout(value=3600)
public Long getResult() {
return result;
}
}
Confidential 25
Initializing Singleton Session Beans
@Startup
@Singleton
@DependsOn({"PrimaryBean",
"SecondaryBean"})
public class CalculationBean
implements CalcLocal, CalcRemote {
private Long result;
@PostConstruct
void construct() {
// any bean initialization ...
result = 0L;
}
………
}
Eager Initialization:
@javax.ejb.Startup
@javax.ejb.DependsOn
Confidential 26
Singleton Session Beans. Errors Handling
• If a singleton session bean encounters an error when
initialized by the EJB container, that singleton instance
will be destroyed
• Singleton instance is not destroyed when methods
causes system exceptions
Confidential 27
Summary: Session Bean Types
Stateless Stateful Singleton
Has no client association Each client has its own
bean instance
Instantiated once per
application
Has no state between calls Stores state between
client calls
Each client obtains single
state
Pooled in memory May be passivated to disk,
cached
-
Client couldn’t manage
lifecycle
Removable by client Client couldn’t manage
lifecycle
Does not support
concurrency
Does not support
concurrency
Supports concurrency
Implements WS Couldn’t implement WS Implements WS
Confidential 28
Accessing Enterprise
Java Beans
Confidential 29
Accessing Session Beans
 Access EJB through a no-interface view or business interface
 no-interface view: invoke any public methods in the EJB class
or superclasses
 Business interface contains the business methods of the EJB
 Session beans can have more than one business interface
Confidential 30
Session Bean Contracts
EJB Contracts
Local
Remote (via
Remote Interface)
As Web Service
Local Interface No-Interface view
Confidential 31
Local Interface Contract
• Run in the same JVM as the EJB
• Client: Web component or another enterprise bean
• Supports pass-by-reference semantics
• The local business interface defines the bean’s business
methods
Confidential 32
Local Bean Declaration
To build an enterprise bean that allows local access:
@Local public interface CalculationLocal { … }
@Stateless
public class CalculationBean implements CalculationLocal { … }
or
public interface CalculationLocal { … }
@Stateless
@Local(CalculationLocal.class)
public class CalculationBean implements CalculationLocal { … }
Confidential 33
Local Contracts. No-Interface view
• No-interface view == local view
• Public methods available for client access
• The client and the target bean must be packaged in the same
application (EAR)
• @Stateless
public class CalculationBean { … }
Confidential 34
Remote Contract
• Client can run on a different JVM
• It can be a web component, an application client, or another
EJB
• Supports pass-by-value semantics
• Must implement a business interface
• Requires creating a stub and a skeleton, which will cost cycles
• Expensive taking time to transfer the object to the client and
create copies (Serializable)
Confidential 35
Remote Bean Declaration
• @Remote
public interface CalculationRemote {…}
@Stateless
public class CalculationBean
implements CalculationRemote {…}
• Or decorate the bean class with @Remote:
public interface CalculationRemote {…}
@Remote(CalculationRemote.class)
public class CalculationBean
implements CalculationRemote {…}
To create an enterprise bean that allows remote access:
Confidential 36
Using Session Beans in Clients
Client obtains Session Bean instances through:
 JNDI lockup (using the Java Naming and Directory
Interface syntax to find the enterprise bean instance)
 dependency injection (using annotations)
Confidential 37
Portable JNDI Syntax
Three JNDI namespaces are used for portable JNDI lookups:
 java:global – remote beans using JNDI
java:global[/application name]/module name/enterprise bean
name[!interface name]
 java:module - local enterprise beans within the same module
(JAR)
java:module/enterprise bean name[!interface name]
 java:app - local enterprise beans packaged within the same
application (EAR)
java:app[/module name]/enterprise bean name[!interface name]
Confidential 38
Lookup Example
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.enterprise.naming.SerialInitContextFactory");
…
InitialContext initialContext = new InitialContext(props);
CalculationLocal bean = (CalculationLocal) initialContext
.lookup("java:app/myapp-
ejb/CalculationBean!net.myapp.service.ejb.CalculationLocal");
Confidential 39
Accessing Beans Using JNDI
• No-Interface view:
CalculationBean bean = (CalculationBean)
initialContext.lookup("java:module/CalculationBean");
• Local:
CalculationLocal bean = (CalculationLocal)
initialContext.lookup("java:module/CalculationBean!
CalculationLocal");
• Remote:
CalculationRemote bean = (CalculationRemote)
initialContext.lookup("java:global/myapp/myapp-
ejb/CalculationBean!CalculationRemote");
Confidential 40
Accessing Beans Using Dependency Injection
• No-Interface view:
@EJB
private CalculationBean bean;
• Local:
@EJB
private CalculationLocal bean;
• Remote:
@EJB
private CalculationRemote bean;
Confidential 41
Ambiguous and overloaded EJB names
@Remote(GreetingService.class)
@Stateless(name="dailyGreetingBean")
public class DailyGreeting implements GreetingService {
}
@Remote(GreetingService.class)
@Stateless(name="weeklyGreetingBean")
public class WeeklyGreeting implements GreetingService {
}
Client:
@Remote(GreetingManager.class)
@Stateless
public class GreetingManagerImpl implements GreetingManager {
@EJB(beanName ="ejbModule.jar#dailyGreetingBean")
GreetingService greetingService;
}
Confidential 42
EJB Register in Deployment Descriptor Example
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MyEJB</ejb-name>
<ejb-local-ref>
<ejb-ref-name>org.examples.MyEJBBean/otherBean
</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>org.examples.MyEJB2LocalBusiness</local>
<ejb-link>MyEJB2</ejb-link>
</ejb-local-ref>
</session>
</enterprise-beans>
</ejb-jar>
@Stateful(name="MyEJB")
public class MyEJBBean implements
MyEJBLocalBusiness
{
@EJB // Field-level injection
private MyEJB2LocalBusiness
otherBean;
}
Confidential 43
Summary: client contracts
Remote Local No Interface View (Local)
Accessed by Interface
@Remote
Accessed by Interface
@Local
Public methods available
for client access
Could be accessed from
another JVM
Accessed from the same
JVM
Accessed from the same
EAR
Supports pass-by-value
semantics
Supports pass-by-
reference semantics
Supports pass-by-
reference semantics
JNDI Lookup or DI (from
the same JVM only)
JNDI Lookup or DI JNDI Lookup or DI
Confidential 44
Messaging and
Message-Driven
Beans
Confidential 45
JMS-Based Message-Driven Beans
Message-driven beans (MDBs) are stateless, server-side,
transaction-aware components for processing asynchronous
messages delivered via JMS
• Able to use all EJB components environment: transactions,
security, resources, concurrency and message acknowledgment
• Does not have a business or component interface
• Identified using the @javax.ejb.MessageDriven annotation or
deployment descriptor
Confidential 46
Activation Config Properties
• @MessageDriven(activationConfig={
@ActivationConfigProperty(
propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(
propertyName = "destination",
propertyValue = "ResourceQueueName"),
@ActivationConfigProperty(
propertyName="messageSelector",
propertyValue="MessageFormat = 'Version 3.4'"),
@ActivationConfigProperty(
propertyName="acknowledgeMode",
propertyValue="Auto-acknowledge")})
public class ReservationProcessorBean implements
javax.jms.MessageListener {
@Override
public void onMessage(Message var1) {...}
}
Confidential 47
MessageListener interface
• javax.jms.MessageListener interface:
public interface MessageListener {
public void onMessage(Message message);
}
• onMessage() Is called, when message arrives
• onMessage() is finished -> MDB ready to process other
message
• MDBs can integrate with other messaging systems
Confidential 48
The Lifecycle of a Message-Driven Bean
• The Method-Ready Pool is
similar to the instance pool
used for stateless beans
• When an MDB instance is in
the Does Not Exist state, it has
not been instantiated yet
• Callbacks : @PostConstruct,
@PreDestroy
Confidential 49
References and
Injections
Confidential 50
Entity Manager Reference
• Entity Manager can be registered in the JNDI Context of an EJB
• EJB container has full control over the lifecycle of the
underlying persistence context of the Entity Manager
• @javax.persistence.PersistenceContext can be used on bean
class’s setter methods or member fields or directly on the class
Confidential 51
Entity Manager Reference
• The @PersistenceContext annotation can also be placed on a
setter method or member field :
@Stateless
public class CalculationBean implements CalculationLocal
{
@PersistenceContext(unitName="MyDB")
private EntityManager em;
}
Confidential 52
Resource Reference
• JNDI Context can be used to look up external resources
• the external resources are mapped into a name within the
JNDI Context by using annotations or DD xml content
• External Resources:
javax.sql.DataSource
javax.jms : Queue, Topic, Connection Factories
javax.mail.Session
java.net.URL
java.lang: String, Character, Byte, Short, Integer, Long, Boolean, Double, Float,
Class, and all Enum types.
Javax.transaction: UserTransaction, TransactionSynchronizationRegistry
CORBA ORB references
JPA PersistenceUnit and PersistenceContext
Confidential 53
Resource Reference Example
@Resource(name="jms/QueueConnectionFactory")
private javax.jms.QueueConnectionFactory
queueConnectionFactory;
@Resource(name="jms/someQueue")
private javax.jms.Queue queue;
@Resource(
name="jdbc/PostgresDB",
type=javax.sql.DataSource.class,
shareable = true,
authenticationType =
AuthenticationType.APPLICATION)
private javax.sql.DataSource dataSource;
Confidential 54
Transactions
Confidential 55
Java EE Transaction Concepts
 Atomicity – operations succeed or fail together
 Locking and isolation – only one transaction at a time can
update a particular piece of data
 Flat transaction model – only one transaction is in effect in a
particular thread at any given time. A transaction cannot be
made up of subtransactions
Confidential 56
Transaction Management Types
javax.ejb .TransactionManagement - specifies session or
message-driven bean transaction management type:
@TransactionManagement(value =
TransactionManagementType.CONTAINER) – default
@TransactionManagement(value =
TransactionManagementType.BEAN)
Confidential 57
Container-Managed Transactions
• Can be used with both of Session and Message-driven bean
types
• The container begins a transaction before method starts and
commits before the method exits
• Each method can be associated with a single transaction
• Do not require all methods to be associated with transactions
• Nested or multiple transactions are not allowed within a
method
• Bean must not use :
- java.sql.Connection commit(), rollback(), setAutoCommit();
- javax.jms.Session commit(), rollback();
- javax.transaction.UserTransaction interface
Confidential 58
CMT: Transaction Attributes
Example: does method B execute with a new Transaction ?
A transaction attribute controls the scope of a Transaction
@javax.ejb.TransactionAttribute
Confidential 59
Transaction Attributes values
Attribute Name Description
Required
(default)
The method becomes part of the caller’s transaction. If the caller
does not have a transaction, the method runs in its own
RequresNew The method always runs in its own transaction. Any existing
transaction is suspended
NotSupported The method never runs in a transaction. Any existing transaction is
suspended
Supports The method becomes part of the caller’s transaction if there is one. If
the caller does not have a transaction, the method does not run in a
transaction
Mandatory It is an error to call this method outside of a transaction
Never It is an error to call this method in a transaction
Confidential 60
Container-Managed Transactions
• EntityManager should be accessed within the JTA transaction
Use Required, RequiresNew and Mandatory type
• MDB only the NotSupported or Required transaction attribute
• The Mandatory transaction attribute cannot be used with EJB
endpoints
• The persistence context is propagated between EJB invocations
in the same transaction
Confidential 61
Transaction Attribute example
@TransactionAttribute(NOT_SUPPORTED)
@Stateful
public class TransactionBean implements Transaction {
...
@TransactionAttribute(REQUIRES_NEW)
public void firstMethod() {...}
@TransactionAttribute(REQUIRED)
public void secondMethod() {...}
public void thirdMethod() {...}
public void fourthMethod() {...}
}
Confidential 62
Bean-Managed Transactions
The JTA specification
 Obtain a reference to the UserTransaction object from
the container
 Scope the transactions using the begin and commit
Methods
 Fail a transaction using the rollback method
Confidential 63
Using the begin, commit, and rollback methods
@Stateful
@TransactionManagement(TransactionManagementType.BEAN)
public class CalculationBean implements CalculationLocal {
@Resource
UserTransaction ut;
public void calculate(…) throws SystemException {
try {
ut.begin(); // Transaction starts here
//... transaction operation 1, 2, 3
ut.commit(); // Transaction finishes here
} catch (Exception e) {
ut.rollback(); // Oops: roll back
}
}
}
Confidential 64
Exception
Handling
Confidential 65
Application and System Exceptions
 Application Exceptions - normally thrown in response to a
business-logic error
 System Exceptions - java.lang.RuntimeException and its
subclasses
Confidential 66
Handling System Exceptions
• EJB Container throws it when encounters an internal
application failure
• Application throws it to abort business process
• Subclasses: EJBException, EJBTransactionRolledBackexception
• Always cause a transaction to roll back
• The container handles automatically :
1. Roll back the transaction
2. Log exception
3. Discard EJB instance
Confidential 67
Handling System Exceptions
• If transaction is started, a system exception (thrown by the
enterprise bean method) will be caught by the container and
rethrown as an EJBTransactionRolledbackException
• If the client did not propagate a transaction to the EJB, the
system exception will be caught and rethrown as an
EJBException
Confidential 68
Handling Application Exceptions
• Always delivered directly to the client without being
repackaged as an EJBException type
• By default, does not cause a transaction to roll back
• To force application Exception to transaction roll back
@javax.ejb.ApplicationException
@ApplicationException(rollback = true)
public class MyException extends Exception
{
...
}
• Can be used with checked and unchecked exceptions, exception
will not be wrapped into EJBException
Confidential 69
What next…
 Security in EJB
 EJB and Web Services
 Interceptors
 Timing Service
 Packaging and deployment
 Vendor-Specific features
 Testing and Mock Containers
Confidential 70
Ссылки
• EJB Oracle Tutorial:
http://docs.oracle.com/javaee/6/tutorial/doc/bnblr.html
• EJB Specification:
http://oracle.com/technetwork/java/docs-135218.html
Confidential 71
Спасибо за внимание
Сергей Болбин
Software developer
Skype sergey.bolbin
Sergey.Bolbin@returnonintelligence.com

Introduction to EJB

  • 1.
    Core Systems TransformationSolutions Enterprise Java Beans Overview. Part 1 October 15, 2015
  • 2.
    Confidential 1 Agenda 1. Overview 2.Session Beans 3. Accessing Session Beans 4. Messaging and MDB 5. References and Injections 6. Transactions 7. Exception Handling
  • 3.
  • 4.
    Confidential 3 What isEJB ? Enterprise Java Beans • is platform for building portable, reusable, and scalable business applications using the Java • is Java components (classes) that executes in a specialized runtime environment called the EJB container
  • 5.
  • 6.
    Confidential 5 EJB containerfunctionality 5 Resources Client ClientSupport Lifecycle Management Resource Management EJB EJB EJB
  • 7.
    Confidential 6 EJB ContainerServices EJB Container provides valuable services for enterprise application development: • Transactions support • Security model • Persistence support • Remote access • Web-services • Interceptors • Thread Safety and Concurrency control • Timing services & job scheduling • Messaging • Asynchronous interactions
  • 8.
    Confidential 7 EJB VersionHistory  EJB 1.1 (J2EE 1.2), 1999 – Session beans (stateful & stateless), Entity Beans – Remote interface  EJB 2.0 (J2EE 1.3), 2001 – Message Driven beans – Entity 2.x and EJB QL – Local & Remote Interfaces  EJB 2.1 (J2EE 1.4), 2003 – EJB Timer Service – EJB QL updates  EJB 3 (2006) , 3.1(2009), 3.2 (2013)
  • 9.
    Confidential 8 Types ofEnterprise Bean Objects • Session Beans • Message-driven beans • Entities
  • 10.
  • 11.
    Confidential 10 Session Beans •Performs specific business-logic operations • Managed by EJB Container • Available for a client session • Is removed when the EJB container crashes • Can be transaction-aware • Can be invoked either locally or remotely using Java RMI
  • 12.
    Confidential 11 Session Beans Sessionbean object is not directly accessed Session EJB component has the following elements: • Component interface • Implementation class
  • 13.
    Confidential 12 Types ofSession Beans • Stateless Session Beans • Stateful Session Beans • Singleton Session Beans
  • 14.
    Confidential 13 Stateless SessionBean • Does not retain client-specific information • A client might not get the same session bean instance • Can implement a web service • Any number of requests can be handled by the same instance
  • 15.
    Confidential 14 Stateless SessionBean EJB EJB EJB EJB EJB Request Instance Pool EJB Container Random Selection
  • 16.
    Confidential 15 Stateless BeanLifecycle and Callbacks @Stateless public class CalculationBean { @PostConstruct void construct() { } @PreDestroy void destroy() { } public int sum(int a, int b) { return a + b; } }
  • 17.
    Confidential 16 Stateless SessionBean Example @Local public interface CalculationLocal { int sum(int a, int b); } @Stateless public class CalculationBean implements CalculationLocal { public int sum(int a, int b) { return a + b; } }
  • 18.
    Confidential 17 Stateful SessionBean • Supports conversation state • Is never shared, has only one client • Client can remove bean instance • Can be passivated by container • Cannot implement a web service
  • 19.
    Confidential 18 Stateful SessionBean EJB id = 3 EJB id = 4 EJB id = 5 EJB id = 1 EJB id = 2 Request Instance Cache EJB Container Select by Session ID ID = 5
  • 20.
    Confidential 19 Stateful BeanLifecycle and Callbacks
  • 21.
    Confidential 20 Stateful BeanLifecycle and Callbacks (Example) @Stateful public class CalculationBean implements CalculationRemote { private int result = 0; @PostConstruct void construct(){} @PreDestroy void destroy(){} @PostActivate void activate(){} @PrePassivate void passivate(){} @Remove public void remove(){} public void add(int a) { result += a; } public int getResult() { return result; } }
  • 22.
    Confidential 21 Singleton SessionBean • Instantiated once per application and exists for the lifecycle of the application • Only one bean per application (jvm) • Does not maintain state across server crashes/shutdowns • Supports concurrency requests • Can implement a web service • Perform tasks upon application startup and shutdown • State shared across the application
  • 23.
    Confidential 22 Singleton SessionBean. Concurrency Management Singleton session beans are designed for concurrent access @javax.ejb.ConcurrencyManagement : - container-managed concurrency javax.ejb.ConcurrencyManagementType.CONTAINER - default - bean-managed concurrency javax.ejb.ConcurrencyManagementType.BEAN
  • 24.
    Confidential 23 Container-Managed concurrency.Locking types Access locking types: javax.ejb.Lock, javax.ejb.LockType - @Lock(LockType.READ) - for read-only operations - @Lock(LockType.WRITE) - default; for exclusive access to the bean instance javax.ejb.AccessTimeout - annotation is used to specify the number of TimeUnits before an access timeout occurs
  • 25.
    Confidential 24 Container-Managed SingletonExample @Singleton @ConcurrencyManagement(CONTAINER) @AccessTimeout(value=20, unit = TimeUnit.SECONDS) public class CalculationBean implements CalculationLocal { private Long result; @PostConstruct void construct() { result = 0L; } @Lock(LockType.WRITE) public void add(int a) { result += a; } @Lock(LockType.READ) @AccessTimeout(value=3600) public Long getResult() { return result; } }
  • 26.
    Confidential 25 Initializing SingletonSession Beans @Startup @Singleton @DependsOn({"PrimaryBean", "SecondaryBean"}) public class CalculationBean implements CalcLocal, CalcRemote { private Long result; @PostConstruct void construct() { // any bean initialization ... result = 0L; } ……… } Eager Initialization: @javax.ejb.Startup @javax.ejb.DependsOn
  • 27.
    Confidential 26 Singleton SessionBeans. Errors Handling • If a singleton session bean encounters an error when initialized by the EJB container, that singleton instance will be destroyed • Singleton instance is not destroyed when methods causes system exceptions
  • 28.
    Confidential 27 Summary: SessionBean Types Stateless Stateful Singleton Has no client association Each client has its own bean instance Instantiated once per application Has no state between calls Stores state between client calls Each client obtains single state Pooled in memory May be passivated to disk, cached - Client couldn’t manage lifecycle Removable by client Client couldn’t manage lifecycle Does not support concurrency Does not support concurrency Supports concurrency Implements WS Couldn’t implement WS Implements WS
  • 29.
  • 30.
    Confidential 29 Accessing SessionBeans  Access EJB through a no-interface view or business interface  no-interface view: invoke any public methods in the EJB class or superclasses  Business interface contains the business methods of the EJB  Session beans can have more than one business interface
  • 31.
    Confidential 30 Session BeanContracts EJB Contracts Local Remote (via Remote Interface) As Web Service Local Interface No-Interface view
  • 32.
    Confidential 31 Local InterfaceContract • Run in the same JVM as the EJB • Client: Web component or another enterprise bean • Supports pass-by-reference semantics • The local business interface defines the bean’s business methods
  • 33.
    Confidential 32 Local BeanDeclaration To build an enterprise bean that allows local access: @Local public interface CalculationLocal { … } @Stateless public class CalculationBean implements CalculationLocal { … } or public interface CalculationLocal { … } @Stateless @Local(CalculationLocal.class) public class CalculationBean implements CalculationLocal { … }
  • 34.
    Confidential 33 Local Contracts.No-Interface view • No-interface view == local view • Public methods available for client access • The client and the target bean must be packaged in the same application (EAR) • @Stateless public class CalculationBean { … }
  • 35.
    Confidential 34 Remote Contract •Client can run on a different JVM • It can be a web component, an application client, or another EJB • Supports pass-by-value semantics • Must implement a business interface • Requires creating a stub and a skeleton, which will cost cycles • Expensive taking time to transfer the object to the client and create copies (Serializable)
  • 36.
    Confidential 35 Remote BeanDeclaration • @Remote public interface CalculationRemote {…} @Stateless public class CalculationBean implements CalculationRemote {…} • Or decorate the bean class with @Remote: public interface CalculationRemote {…} @Remote(CalculationRemote.class) public class CalculationBean implements CalculationRemote {…} To create an enterprise bean that allows remote access:
  • 37.
    Confidential 36 Using SessionBeans in Clients Client obtains Session Bean instances through:  JNDI lockup (using the Java Naming and Directory Interface syntax to find the enterprise bean instance)  dependency injection (using annotations)
  • 38.
    Confidential 37 Portable JNDISyntax Three JNDI namespaces are used for portable JNDI lookups:  java:global – remote beans using JNDI java:global[/application name]/module name/enterprise bean name[!interface name]  java:module - local enterprise beans within the same module (JAR) java:module/enterprise bean name[!interface name]  java:app - local enterprise beans packaged within the same application (EAR) java:app[/module name]/enterprise bean name[!interface name]
  • 39.
    Confidential 38 Lookup Example Propertiesprops = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory"); … InitialContext initialContext = new InitialContext(props); CalculationLocal bean = (CalculationLocal) initialContext .lookup("java:app/myapp- ejb/CalculationBean!net.myapp.service.ejb.CalculationLocal");
  • 40.
    Confidential 39 Accessing BeansUsing JNDI • No-Interface view: CalculationBean bean = (CalculationBean) initialContext.lookup("java:module/CalculationBean"); • Local: CalculationLocal bean = (CalculationLocal) initialContext.lookup("java:module/CalculationBean! CalculationLocal"); • Remote: CalculationRemote bean = (CalculationRemote) initialContext.lookup("java:global/myapp/myapp- ejb/CalculationBean!CalculationRemote");
  • 41.
    Confidential 40 Accessing BeansUsing Dependency Injection • No-Interface view: @EJB private CalculationBean bean; • Local: @EJB private CalculationLocal bean; • Remote: @EJB private CalculationRemote bean;
  • 42.
    Confidential 41 Ambiguous andoverloaded EJB names @Remote(GreetingService.class) @Stateless(name="dailyGreetingBean") public class DailyGreeting implements GreetingService { } @Remote(GreetingService.class) @Stateless(name="weeklyGreetingBean") public class WeeklyGreeting implements GreetingService { } Client: @Remote(GreetingManager.class) @Stateless public class GreetingManagerImpl implements GreetingManager { @EJB(beanName ="ejbModule.jar#dailyGreetingBean") GreetingService greetingService; }
  • 43.
    Confidential 42 EJB Registerin Deployment Descriptor Example <ejb-jar> <enterprise-beans> <session> <ejb-name>MyEJB</ejb-name> <ejb-local-ref> <ejb-ref-name>org.examples.MyEJBBean/otherBean </ejb-ref-name> <ejb-ref-type>Session</ejb-ref-type> <local>org.examples.MyEJB2LocalBusiness</local> <ejb-link>MyEJB2</ejb-link> </ejb-local-ref> </session> </enterprise-beans> </ejb-jar> @Stateful(name="MyEJB") public class MyEJBBean implements MyEJBLocalBusiness { @EJB // Field-level injection private MyEJB2LocalBusiness otherBean; }
  • 44.
    Confidential 43 Summary: clientcontracts Remote Local No Interface View (Local) Accessed by Interface @Remote Accessed by Interface @Local Public methods available for client access Could be accessed from another JVM Accessed from the same JVM Accessed from the same EAR Supports pass-by-value semantics Supports pass-by- reference semantics Supports pass-by- reference semantics JNDI Lookup or DI (from the same JVM only) JNDI Lookup or DI JNDI Lookup or DI
  • 45.
  • 46.
    Confidential 45 JMS-Based Message-DrivenBeans Message-driven beans (MDBs) are stateless, server-side, transaction-aware components for processing asynchronous messages delivered via JMS • Able to use all EJB components environment: transactions, security, resources, concurrency and message acknowledgment • Does not have a business or component interface • Identified using the @javax.ejb.MessageDriven annotation or deployment descriptor
  • 47.
    Confidential 46 Activation ConfigProperties • @MessageDriven(activationConfig={ @ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty( propertyName = "destination", propertyValue = "ResourceQueueName"), @ActivationConfigProperty( propertyName="messageSelector", propertyValue="MessageFormat = 'Version 3.4'"), @ActivationConfigProperty( propertyName="acknowledgeMode", propertyValue="Auto-acknowledge")}) public class ReservationProcessorBean implements javax.jms.MessageListener { @Override public void onMessage(Message var1) {...} }
  • 48.
    Confidential 47 MessageListener interface •javax.jms.MessageListener interface: public interface MessageListener { public void onMessage(Message message); } • onMessage() Is called, when message arrives • onMessage() is finished -> MDB ready to process other message • MDBs can integrate with other messaging systems
  • 49.
    Confidential 48 The Lifecycleof a Message-Driven Bean • The Method-Ready Pool is similar to the instance pool used for stateless beans • When an MDB instance is in the Does Not Exist state, it has not been instantiated yet • Callbacks : @PostConstruct, @PreDestroy
  • 50.
  • 51.
    Confidential 50 Entity ManagerReference • Entity Manager can be registered in the JNDI Context of an EJB • EJB container has full control over the lifecycle of the underlying persistence context of the Entity Manager • @javax.persistence.PersistenceContext can be used on bean class’s setter methods or member fields or directly on the class
  • 52.
    Confidential 51 Entity ManagerReference • The @PersistenceContext annotation can also be placed on a setter method or member field : @Stateless public class CalculationBean implements CalculationLocal { @PersistenceContext(unitName="MyDB") private EntityManager em; }
  • 53.
    Confidential 52 Resource Reference •JNDI Context can be used to look up external resources • the external resources are mapped into a name within the JNDI Context by using annotations or DD xml content • External Resources: javax.sql.DataSource javax.jms : Queue, Topic, Connection Factories javax.mail.Session java.net.URL java.lang: String, Character, Byte, Short, Integer, Long, Boolean, Double, Float, Class, and all Enum types. Javax.transaction: UserTransaction, TransactionSynchronizationRegistry CORBA ORB references JPA PersistenceUnit and PersistenceContext
  • 54.
    Confidential 53 Resource ReferenceExample @Resource(name="jms/QueueConnectionFactory") private javax.jms.QueueConnectionFactory queueConnectionFactory; @Resource(name="jms/someQueue") private javax.jms.Queue queue; @Resource( name="jdbc/PostgresDB", type=javax.sql.DataSource.class, shareable = true, authenticationType = AuthenticationType.APPLICATION) private javax.sql.DataSource dataSource;
  • 55.
  • 56.
    Confidential 55 Java EETransaction Concepts  Atomicity – operations succeed or fail together  Locking and isolation – only one transaction at a time can update a particular piece of data  Flat transaction model – only one transaction is in effect in a particular thread at any given time. A transaction cannot be made up of subtransactions
  • 57.
    Confidential 56 Transaction ManagementTypes javax.ejb .TransactionManagement - specifies session or message-driven bean transaction management type: @TransactionManagement(value = TransactionManagementType.CONTAINER) – default @TransactionManagement(value = TransactionManagementType.BEAN)
  • 58.
    Confidential 57 Container-Managed Transactions •Can be used with both of Session and Message-driven bean types • The container begins a transaction before method starts and commits before the method exits • Each method can be associated with a single transaction • Do not require all methods to be associated with transactions • Nested or multiple transactions are not allowed within a method • Bean must not use : - java.sql.Connection commit(), rollback(), setAutoCommit(); - javax.jms.Session commit(), rollback(); - javax.transaction.UserTransaction interface
  • 59.
    Confidential 58 CMT: TransactionAttributes Example: does method B execute with a new Transaction ? A transaction attribute controls the scope of a Transaction @javax.ejb.TransactionAttribute
  • 60.
    Confidential 59 Transaction Attributesvalues Attribute Name Description Required (default) The method becomes part of the caller’s transaction. If the caller does not have a transaction, the method runs in its own RequresNew The method always runs in its own transaction. Any existing transaction is suspended NotSupported The method never runs in a transaction. Any existing transaction is suspended Supports The method becomes part of the caller’s transaction if there is one. If the caller does not have a transaction, the method does not run in a transaction Mandatory It is an error to call this method outside of a transaction Never It is an error to call this method in a transaction
  • 61.
    Confidential 60 Container-Managed Transactions •EntityManager should be accessed within the JTA transaction Use Required, RequiresNew and Mandatory type • MDB only the NotSupported or Required transaction attribute • The Mandatory transaction attribute cannot be used with EJB endpoints • The persistence context is propagated between EJB invocations in the same transaction
  • 62.
    Confidential 61 Transaction Attributeexample @TransactionAttribute(NOT_SUPPORTED) @Stateful public class TransactionBean implements Transaction { ... @TransactionAttribute(REQUIRES_NEW) public void firstMethod() {...} @TransactionAttribute(REQUIRED) public void secondMethod() {...} public void thirdMethod() {...} public void fourthMethod() {...} }
  • 63.
    Confidential 62 Bean-Managed Transactions TheJTA specification  Obtain a reference to the UserTransaction object from the container  Scope the transactions using the begin and commit Methods  Fail a transaction using the rollback method
  • 64.
    Confidential 63 Using thebegin, commit, and rollback methods @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class CalculationBean implements CalculationLocal { @Resource UserTransaction ut; public void calculate(…) throws SystemException { try { ut.begin(); // Transaction starts here //... transaction operation 1, 2, 3 ut.commit(); // Transaction finishes here } catch (Exception e) { ut.rollback(); // Oops: roll back } } }
  • 65.
  • 66.
    Confidential 65 Application andSystem Exceptions  Application Exceptions - normally thrown in response to a business-logic error  System Exceptions - java.lang.RuntimeException and its subclasses
  • 67.
    Confidential 66 Handling SystemExceptions • EJB Container throws it when encounters an internal application failure • Application throws it to abort business process • Subclasses: EJBException, EJBTransactionRolledBackexception • Always cause a transaction to roll back • The container handles automatically : 1. Roll back the transaction 2. Log exception 3. Discard EJB instance
  • 68.
    Confidential 67 Handling SystemExceptions • If transaction is started, a system exception (thrown by the enterprise bean method) will be caught by the container and rethrown as an EJBTransactionRolledbackException • If the client did not propagate a transaction to the EJB, the system exception will be caught and rethrown as an EJBException
  • 69.
    Confidential 68 Handling ApplicationExceptions • Always delivered directly to the client without being repackaged as an EJBException type • By default, does not cause a transaction to roll back • To force application Exception to transaction roll back @javax.ejb.ApplicationException @ApplicationException(rollback = true) public class MyException extends Exception { ... } • Can be used with checked and unchecked exceptions, exception will not be wrapped into EJBException
  • 70.
    Confidential 69 What next… Security in EJB  EJB and Web Services  Interceptors  Timing Service  Packaging and deployment  Vendor-Specific features  Testing and Mock Containers
  • 71.
    Confidential 70 Ссылки • EJBOracle Tutorial: http://docs.oracle.com/javaee/6/tutorial/doc/bnblr.html • EJB Specification: http://oracle.com/technetwork/java/docs-135218.html
  • 72.
    Confidential 71 Спасибо завнимание Сергей Болбин Software developer Skype sergey.bolbin Sergey.Bolbin@returnonintelligence.com

Editor's Notes

  • #5 From a developer’s point of view, an EJB is a piece of Java code that executes in a specialized runtime environment called the EJB container, which provides a number of component services. EJB = server-side components that you can use to build parts of your application, such as the business logic or persistence code. A component is what it ought to be—nothing more than a POJO with some special powers.
  • #7 The EJB container provides the following functionality: • Encapsulates access to external resources such as databases and legacy systems • Manages the life cycles of instances of the EJB component’s implementation class • Isolates the class that provides the implementation from its clients • Provides timer services, and can invoke methods at certain times, which allows the EJB component to perform scheduled tasks • Monitors, for message-driven beans, a message queue on behalf of the EJB component
  • #9 EJB 3.2, final release (2013-05-28) JSR 345. Enterprise JavaBeans 3.2 was a relatively minor release that mainly contained specification clarifications and lifted some restrictions that were imposed by the spec but overtime appeared to serve no real purpose. A few existing full EJB features were also demanded to be in EJB 3 lite and functionality that was proposed to be pruned in EJB 3.1 was indeed pruned (made optional).  The following features were added: Passivation of a stateful session bean can be deactivated via attribute on @Stateful annotation (passivationCapable = false) TimerService can retrieve all active timers in the same EJB module (could previously only retrieve timers for the bean in which the TimerService was called) Lifecycle methods (e.g. @PostConstruct) can be transactional for stateful session beans using the existing @TransactionAttribute annotation Autocloseable interface implemented by embeddable container EJB 3.1, final release (2009-12-10) JSR 318. The purpose of the Enterprise JavaBeans 3.1 specification is to further simplify the EJB architecture by reducing its complexity from the developer's point of view, while also adding new functionality in response to the needs of the community: Local view without interface (No-interface view) .war packaging of EJB components EJB Lite: definition of a subset of EJB Portable EJB Global JNDI Names Singletons (Singleton Session Beans) Application Initialization and Shutdown Events EJB Timer Service Enhancements Simple Asynchrony (@Asynchronous for session beans) EJB 3.0, final release (2006-05-11) JSR 220 - Major changes: This release made it much easier to write EJBs, using 'annotations' rather than the complex 'deployment descriptors' used in version 2.x. The use of home and remote interfaces and the ejb-jar.xml file were also no longer required in this release, having been replaced with a business interface and a bean that implements the interface.
  • #12  A session bean is invoked by a client for the purpose of performing a specific business operation, such as checking the credit history for a customer. The name session implies that a bean instance is available for the duration of a “unit of work” and does not survive a server crash or shutdown. A session bean can model any application logic functionality. There are two types of session beans: stateful and stateless. A stateful session bean automatically saves bean state between client invocations without your having to write any additional code. A typical example of a state-aware process is the shopping cart for a web merchant like Amazon. In contrast, stateless session beans do not maintain any state and model application services that can be completed in a single client invocation. You could build stateless session beans for implementing business processes such as charging a credit card or checking customer credit history. A session bean can be invoked either locally or remotely using Java RMI. A stateless session bean can be exposed as a web service.
  • #13 proxy reference the client does not access the EJB directly, which allows the Container to perform all sorts of magic before a request finally hits the target method. It’s this separation that allows for the client to be completely unaware of the location of the server, concurrency policies, or queuing of requests to manage resources. As far as the client is concerned, it’s operating directly upon an EJB. In truth, the client is invoking upon a proxy reference that will delegate the request along to the Container and return the appropriate response
  • #14 Stateful Session Beans The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client/bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. When the client terminates, its session bean appears to terminate and is no longer associated with the client. The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state. Stateless Session Beans variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean should apply across all clients. Because they can support multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients. A stateless session bean can implement a web service, but a stateful session bean cannot. Singleton Session Beans A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients. Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints. Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns. Applications that use a singleton session bean may specify that the singleton should be instantiated upon application startup, which allows the singleton to perform initialization tasks for the application. The singleton may perform cleanup tasks on application shutdown as well, because the singleton will operate throughout the lifecycle of the application.
  • #15 Any number of client requests can be handled by the same session bean instance. This has a profound impact on performance
  • #16 By default, no stateless session EJB instances exist in WebLogic Server at startup time. As individual beans are invoked, WebLogic Server initializes new instances of the EJB. However, in a production environment, WebLogic Server can provide improved performance and throughput for stateless session EJBs by maintaining a free pool of unbound stateless session EJBs—instances that are not currently processing a method call. If an unbound instance is available to serve a request, response time improves, because the request does not have to wait for an instance to be created. The free pool improves performance by reusing objects and skipping container callbacks when it can. Upon startup, WebLogic Server automatically creates and populates the free pool with the quantity of instances you specify in the bean's initial-beans-in-free-pool deployment element in the weblogic-ejb-jar.xml file. By default, initial-beans-in-free-pool is set to 0. The following figure illustrates the WebLogic Server free pool, and the processes by which stateless EJBs enter and leave the pool. Dotted lines indicate the "state" of the EJB from the perspective of WebLogic Server.
  • #17 Контейнер выполняет инъекции всех зависимостей и затем вызывает метод, аннотированный @PostConstruct(после конструирования), если таковой имеется. Теперь бин готов к тому, чтобы выполнять методы бизнес логики, вызываемые клиентом. Because a stateless session bean is never passivated, its life cycle has only two stages: nonexistent and ready for the invocation of business methods. Figure 20-4 illustrates the stages of a stateless session bean. The EJB container typically creates and maintains a pool of stateless session beans, beginning the stateless session bean’s lifecycle. The container performs any dependency injection and then invokes the method annotated @PostConstruct, if it exists. The bean is now ready to have its business methods invoked by a client. At the end of the lifecycle, the EJB container calls the method annotated @PreDestroy, if it exists. The bean’s instance is then ready for garbage collection.
  • #20 http://docs.oracle.com/cd/E13222_01/wls/docs81/ejb/session.html
  • #21 Stateful: Контейнер EJB может решить дезактивировать или перевести в пассивный режим бин, находящийся на стадии готовности, путем перемещения его из основной памяти во вторичный источник хранения. Непосредственно перед переводом бина в пассивный режим EJB контейнер вызывает метод, аннотированный как @PrePassivate(перед пассивированием), если таковой имеется. Если клиентом будет произведен вызов методов бизнес логики бина, находящегося в пассивной стадии, то EJB контейнер активирует бин, вызвав метод аннотированный как @PostActivate(после активизации), если таковой имеется в бине, и затем переведет его в стадию готовности. В конце жизненного цикла клиент инициирует вызов метода аннотированного как @Remove(удалить), и контейнер EJB вызывает метод аннотированный как @PreDestroy(перед разрушением), опять же, если таковой имеется. Теперь экземпляр бина готов быть обработанным сборщиком мусора.
  • #22 Stateful: Контейнер EJB может решить дезактивировать или перевести в пассивный режим бин, находящийся на стадии готовности, путем перемещения его из основной памяти во вторичный источник хранения. Непосредственно перед переводом бина в пассивный режим EJB контейнер вызывает метод, аннотированный как @PrePassivate(перед пассивированием), если таковой имеется. Если клиентом будет произведен вызов методов бизнес логики бина, находящегося в пассивной стадии, то EJB контейнер активирует бин, вызвав метод аннотированный как @PostActivate(после активизации), если таковой имеется в бине, и затем переведет его в стадию готовности. В конце жизненного цикла клиент инициирует вызов метода аннотированного как @Remove(удалить), и контейнер EJB вызывает метод аннотированный как @PreDestroy(перед разрушением), опять же, если таковой имеется. Теперь экземпляр бина готов быть обработанным сборщиком мусора.
  • #23 Offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans.
  • #24 If a method is of locking type WRITE, client access to all the singleton’s methods is blocked until the current client finishes its method call or an access timeout occurs. When an access timeout occurs, the EJB container throws a javax.ejb.ConcurrentAccessTimeoutException. The javax.ejb.AccessTimeout annotation is used to specify the number of milliseconds before an access timeout occurs. If added at the class level of a singleton, @AccessTimeout specifies the access timeout value for all methods in the singleton unless a method explicitly overrides the default with its own @AccessTimeout annotation. https://docs.oracle.com/cd/E19798-01/821-1841/gipsz/index.html Singletons that use bean-managed concurrency allow full concurrent access to all the business and timeout methods in the singleton. The developer of the singleton is responsible for ensuring that the state of the singleton is synchronized across all clients. Developers who create singletons with bean-managed concurrency are allowed to use the Java programming language synchronization primitives, such as synchronization and volatile, to prevent errors during concurrent access.
  • #25 EJB container controls client access to the business methods of the singleton. Access timeout: - value > 0 timeout value in the units specified by the unit element; - value = 0 concurrent access is not permitted; - value = -1 request will block indefinitely until forward progress it can proceed.
  • #31  Client access enterprise beans either through a no-interface view or through a business interface Clients using the no-interface view of an enterprise bean may invoke any public methods in the enterprise bean implementation class or any superclasses A business interface contains the business methods of the enterprise bean All other aspects of the enterprise bean (method implementations and deployment settings) are hidden from the client. Session beans can have more than one business interface
  • #32 Bean has a @LocalBean annotation -> bean has a no-interface view
  • #33 It must run in the same application as the enterprise bean it accesses It can be a web component or another enterprise bean To the local client, the location of the enterprise bean it accesses is not transparent Supports pass-by-reference semantics The local business interface defines the bean’s business and lifecycle methods If the bean’s business interface is not decorated with @Local or @Remote, and if the bean class does not specify the interface using @Local or @Remote, the business interface is by default a local interface
  • #34 To build an enterprise bean that allows only local access, you may, but are not required to, do one of the following: Create an EJB implementation class that does not implement a business interface: @Session public class MyBean { ... } Annotate the business interface of the enterprise bean as a @Local interface: @Local public interface InterfaceName { ... } Specify the interface by decorating the bean class with @Local and specify the interface name: @Local(InterfaceName.class) public class BeanName implements InterfaceName { ... }
  • #35 The no-interface view of an enterprise bean is a local view The public methods of the enterprise bean implementation class are exposed to local clients that access the no-interface view of the enterprise bean In case of no-interface view, the client and the target bean must be packaged in the same application (EAR) In case of local view, client can be packaged in a separate application than the enterprise application
  • #36 To specify that an EJB component will use pass by reference semantics, use the following tag in the sun-ejb-jar.xml deployment descriptor: <pass-by-reference>true</pass-by-reference>. This avoids copying arguments when the EJB component’s methods are invoked and avoids copying results when methods return. However, problems will arise if the data is modified by another source during the invocation. Can run on a different machine and a different JVM from the enterprise bean it accesses. It can be a web component, an application client, or another enterprise bean. To a remote client, the location of the enterprise bean is transparent. The enterprise bean must implement a business interface. That is, remote clients may not access an enterprise bean through a no-interface view. Creating a remote object requires creating a stub and a skeleton, which will cost cycles. Returning a remote object is somewhat expensive, taking time to transfer the object to the client and create copies Isolation The parameters of remote calls are more isolated than those of local calls. With remote calls, the client and the bean operate on different copies of a parameter object. If the client changes the value of the object, the value of the copy in the bean does not change. This layer of isolation can help protect the bean if the client accidentally modifies the data. In a local call, both the client and the bean can modify the same parameter object. In general, you should not rely on this side effect of local calls. Perhaps someday you will want to distribute your components, replacing the local calls with remote ones. As with remote clients, web service clients operate on different copies of parameters than does the bean that implements the web service.
  • #38 Dependency injection is the simplest way of obtaining an enterprise bean reference. Clients that run within a Java EE server-managed environment, JavaServer Faces web applications, JAX-RS web services, other enterprise beans, or Java EE application clients, support dependency injection using the javax.ejb.EJB annotation. Applications that run outside a Java EE server-managed environment, such as Java SE applications, must perform an explicit lookup. JNDI supports a global syntax for identifying Java EE components to The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard. simplify this explicit lookup.
  • #39 Three JNDI namespaces are used for portable JNDI lookups: java:global, java:module, and java:app. The java:global JNDI namespace is the portable way of finding remote enterprise beans using JNDI lookups. JNDI addresses are of the following form: java:global[/application name]/module name/enterprise bean name[/interface name] Application name and module name default to the name of the application and module minus the file extension. Application names are required only if the application is packaged within an EAR. The interface name is required only if the enterprise bean implements more than one business interface. The java:module namespace is used to look up local enterprise beans within the same module. JNDI addresses using the java:module namespace are of the following form: java:module/enterprise bean name/[interface name]The interface name is required only if the enterprise bean implements more than one business interface. The java:app namespace is used to look up local enterprise beans packaged within the same application. That is, the enterprise bean is packaged within an EAR file containing multiple Java EE modules. JNDI addresses using the java:app namespace are of the following form: java:app[/module name]/enterprise bean name[/interface name]The module name is optional. The interface name is required only if the enterprise bean implements more than one business interface. For example, if an enterprise bean, MyBean, is packaged within the web application archive myApp.war, the module name is myApp. The portable JNDI name is java:module/MyBean An equivalent JNDI name using the java:global namespace is java:global/myApp/MyBean.
  • #41 To build an enterprise bean that allows only local access, you may, but are not required to, do one of the following:
  • #42 To build an enterprise bean that allows only local access, you may, but are not required to, do one of the following:
  • #43 The <ejb-name> element and any @Stateless.name() or @Stateful.name() attributes must be unique within a given EJB-JAR deployment. Unfortunately, this is not the case for all EJB JARs deployed in an Enterprise ARchive (.ear) file. In an .ear file, EJB names can be duplicated in different EJB-JAR deployments. To differentiate references with duplicate EJB names, the EJB specification has an extended syntax for <ejb-link> and the beanName() attribute of the @EJB annotation. This extended syntax has a relative path to the JAR file in which the EJB is located, followed by the # character, followed by the EJB name of the referenced bean:
  • #45 The <ejb-name> element and any @Stateless.name() or @Stateful.name() attributes must be unique within a given EJB-JAR deployment. Unfortunately, this is not the case for all EJB JARs deployed in an Enterprise ARchive (.ear) file. In an .ear file, EJB names can be duplicated in different EJB-JAR deployments. To differentiate references with duplicate EJB names, the EJB specification has an extended syntax for <ejb-link> and the beanName() attribute of the @EJB annotation. This extended syntax has a relative path to the JAR file in which the EJB is located, followed by the # character, followed by the EJB name of the referenced bean:
  • #47 The thread safety provided by the container gives MDBs a significant advantage over traditional JMS clients, which must be custom built to manage resources, transactions, and security in a multithreaded environment. An MDB can process hundreds of JMS messages concurrently because many underlying bean instances of the MDB can execute concurrently in the container. While a message-driven bean has a bean class, it does not have a business or component interface. These are absent because the message-driven bean responds only to asynchronous messages and not to direct client invocations.
  • #48 @MessageDriven.activationConfig() attribute takes an array of @ActivationConfigProperty annotations. These annotations are simply a set of generic name/value pairs that describe the configuration of your MDB.
  • #49 As messages arrive, the container passes them to the MDB via the onMessage() method When the method returns, the MDB instance is ready to process a new message
  • #50 The Method-Ready Pool MDB instances enter the Method-Ready Pool as the container needs them. When theEJB server is first started, it may create a number of MDB instances and enter them into the Method-Ready Pool (the actual behavior of the server depends on the implementation). When the number of MDB instances handling incoming messages is insufficient, more can be created and added to the pool. When an instance transitions from the Does Not Exist state to the Method-Ready Pool, three operations are performed on it. First, the bean instance is instantiated by invoking the Class.newInstance() method on the bean implementation class. Second, the container injects any resources that the bean’s metadata has requested via an injection annotation or XML deployment descriptor.
  • #52 The name() attribute refers to the JNDI ENC name under which the EntityManager is referenced. This name is relative to the java:comp/env context. The unitName() attribute identifies which persistence unit you are interested in referencing. This identifier is the same as what you have declared in your persistence.xml file. If left unspecified, a deployment error is raised unless the EJB-JAR has only one persistence unit deployed within it. In that case, it defaults to this sole persistence unit. The type() attribute specifies the type of persistence context you want. Persistence ContextType.TRANSACTION specifies that you want a transaction-scoped persistence context. This is the default. PersistenceContextType.EXTENDED gives you an extended persistence context. The EXTENDED type can be used only on stateful session beans. You will receive a deployment error if you use it with any other bean type. The properties() attribute allows you to pass in additional vendor-specific properties for the created EntityManager instance. You set this attribute with an array of @javax.persistence.PersistenceProperty annotation declarations.
  • #54 EJBs need access to more than just other EJBs and persistence contexts, and they use the JNDI ENC to look up external resources that they need to access. The mechanism for doing this is similar to the mechanism used for referencing other EJB and environment entries: the external resources are mapped into a name within the JNDI ENC namespace and are optionally injected into member fields or setter methods of bean instances. This is accomplished using annotations or an XML deployment descriptor fragment.
  • #55 The @Resource annotation can be used only once on your bean class. When you need to reference multiple persistence units, the @javax.annotation.Resources annotation is available. The @Resource annotation can also be placed on a setter method or member field so that the resources referenced will be injected directly into the bean class instance. When used on a setter method or member field, only the lookup() attribute may be required to identify the resource, as the type and ENC name can be determined from the type and name of the method or field. The authenticationType() attribute tells the server who is responsible for authentication when the resource is accessed. It can have one of two values: CONTAINER or APPLICATION. If CONTAINER is specified, the container will automatically perform authentication (sign on or log in) to use the resource, as specified at deployment time. If APPLICATION is specified, the bean itself must perform the authentication before using the resource. Shareable resources When several enterprise beans in a transaction use the same resource, you will want to configure your EJB server to share that resource. Sharing a resource means that each EJB will use the same connection to access the resource (e.g., database or JMS provider), a strategy that is more efficient than using separate resource connections. In terms of a database, EJBs that are referencing the same database will probably want to use the same database connection during a transaction so that all create, read, update, and delete (CRUD) operations return consistent results. EJB containers share resources by default, but resource sharing can be turned on or off explicitly with the shareable() attribute of the @Resource annotation. Occasionally, advanced developers may run into situations where resource sharing is not desirable, and having the option to turn off resource sharing is beneficial. But unless you have a good reason for turning off resource sharing, we recommend that you accept the default shareable() setting of true.
  • #58 Container-Managed transactions (CMT) The EJB container controls the integrity of transactions without having to call commit or rollback Bean-Managed transactions transaction boundaries defined by bean method realization by using commit and rollback methods of UserTransaction . javax.ejb .TransactionManagement - annotation, that specifies session or message driven bean transaction management type: @TransactionManagement(value = TransactionManagementType.CONTAINER) – default @TransactionManagement(value = TransactionManagementType.BEAN)
  • #60 A transaction attribute controls the scope of a transaction. Figure 44–1 illustrates why controlling the scope is important. In the diagram, method-A begins a transaction and then invokes method-B of Bean-2. When method-B executes, does it run within the scope of the transaction started by method-A, or does it execute with a new transaction? The answer depends on the transaction attribute of method-B.
  • #61 RequiresNewAttribute If the client is running within a transaction and invokes the enterprise bean’s method, the container takes the following steps: 1. Suspends the client’s transaction 2. Starts a new transaction 3. Delegates the call to the method 4. Resumes the client’s transaction after the method completes If the client is not associated with a transaction, the container starts a new transaction before running the method. You should use the RequiresNew attribute when you want to ensure that the method always runs within a new transaction. Mandatory Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction. If the client is not associated with a transaction, the container throws a TransactionRequiredException. Use the Mandatory attribute if the enterprise bean’s method must use the transaction of the client. NotSupported Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the container suspends the client’s transaction before invoking the method. After the method has completed, the container resumes the client’s transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. Use the NotSupported attribute for methods that don’t need transactions. Because transactions involve overhead, this attribute may improve performance. Supports Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. Because the transactional behavior of the method may vary, you should use the Supports attribute with caution. Never Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException. If the client is not associated with a transaction, the container does not start a new transaction before running the method. The EJB specification strongly advises that EntityManagers be accessed within the scope of a JTA transaction. So, if you are wrapping access to your persistent entities with EJBs, use only the Required, RequiresNew, and Mandatory transaction attributes.
  • #62 EJB 3.0 persistence and transaction attributes The EJB specification strongly advises that EntityManagers be accessed within the scope of a JTA transaction. So, if you are wrapping access to your persistent entities with EJBs, use only the Required, RequiresNew, and Mandatory transaction attributes. This restriction ensures that all database access occurs in the context of a transaction, which is important when the container is automatically managing persistence. There are valid exceptions to this rule when using extended persistence contexts with stateful session beans, but we’ll talk about these exceptions later in the chapter. Message-driven beans and transaction attributes Message-driven beans may declare only the NotSupported or Required transaction attribute. The other transaction attributes don’t make sense in message-driven beans, because they apply to client-initiated transactions. The Supports, RequiresNew, Mandatory, and Never attributes are all relative to the transaction context of the client. For example, the Mandatory attribute requires the client to have a transaction in progress before calling the enterprise bean. This is meaningless for a message-driven bean, which is decoupled from the client. The NotSupported transaction attribute indicates that the message will be processed without a transaction. The Required transaction attribute indicates that the message will be processed with a container-initiated transaction. • When a transaction-scoped entity manager is invoked outside the scope of a transaction, it creates a persistence context for the duration of that method call. After the method call completes, any managed objects produced by the call are immediately detached. • If a transaction-scoped entity manager is invoked from within a transaction, a new persistence context is created (if there isn’t one already) and associated with that transaction. • If an entity manager is invoked upon and a persistence context is already associated with the transaction, use that persistence context. The persistence context is propagated between EJB invocations in the same transaction. This means that if an EJB interacts with an injected entity manager within a transaction and then invokes on another EJB within that same transaction, that EJB call will use the same enlisted persistence context. • If an EJB with a transaction-scoped persistence context invokes on a stateful session bean that uses an extended persistence context, an error is thrown. If a stateful session bean with an extended persistence context calls another EJB that has injected a transaction-scoped persistence context, the extended persistence context is propagated. • If an EJB calls another EJB with a different transaction scope, the persistence context, regardless of whether it is extended, is not propagated. • If a stateful session bean with an extended persistence context calls another noninjected stateful session bean with an extended persistence context, an error is thrown. If you inject a stateful session bean into another stateful session bean, those beans share the same extended persistence context. However, if you manually create a stateful session, there is no sharing of persistence contexts.
  • #63 RequiresNewAttribute If the client is running within a transaction and invokes the enterprise bean’s method, the container takes the following steps: 1. Suspends the client’s transaction 2. Starts a new transaction 3. Delegates the call to the method 4. Resumes the client’s transaction after the method completes If the client is not associated with a transaction, the container starts a new transaction before running the method. You should use the RequiresNew attribute when you want to ensure that the method always runs within a new transaction. Mandatory Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction. If the client is not associated with a transaction, the container throws a TransactionRequiredException. Use the Mandatory attribute if the enterprise bean’s method must use the transaction of the client. NotSupported Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the container suspends the client’s transaction before invoking the method. After the method has completed, the container resumes the client’s transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. Use the NotSupported attribute for methods that don’t need transactions. Because transactions involve overhead, this attribute may improve performance. Supports Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. Because the transactional behavior of the method may vary, you should use the Supports attribute with caution. Never Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException. If the client is not associated with a transaction, the container does not start a new transaction before running the method.
  • #67 https://www.ibm.com/developerworks/library/j-ejbexcept/
  • #68 When a system exception is thrown from any callback method (@PostConstruct, @Post Activate, and so on), it is treated the same way as exceptions thrown from any business Method The impact of discarding an EJB instance depends on the enterprise bean’s type. In the case of stateless session beans, the client does not notice that the instance has been discarded. These instance types are not dedicated to a particular client; they are swapped in and out of an instance pool, and so any instance can service a new request. With stateful session beans, however, the impact on the client is severe. Stateful session beans are dedicated to a single client and maintain conversational state. Discarding a stateful bean instance destroys the instance’s conversational state and invalidates the client’s reference to the EJB. When stateful session instances are discarded, subsequent invocations of the EJB’s methods by the client result in a NoSuchEJBException, which is a subclass of RuntimeException.§ With message-driven beans, a system exception thrown by the onMessage() method or one of the callback methods (@PostConstruct or @PreDestroy) will cause the bean instance to be discarded. If the MDB was a BMT bean, the message it was handling may or may not be redelivered, depending on when the EJB container acknowledges delivery. In the case of container-managed transactions, the container will roll back the transaction, so the message will not be acknowledged and may be redelivered.
  • #69 When a system exception is thrown from any callback method (@PostConstruct, @Post Activate, and so on), it is treated the same way as exceptions thrown from any business Method The impact of discarding an EJB instance depends on the enterprise bean’s type. In the case of stateless session beans, the client does not notice that the instance has been discarded. These instance types are not dedicated to a particular client; they are swapped in and out of an instance pool, and so any instance can service a new request. With stateful session beans, however, the impact on the client is severe. Stateful session beans are dedicated to a single client and maintain conversational state. Discarding a stateful bean instance destroys the instance’s conversational state and invalidates the client’s reference to the EJB. When stateful session instances are discarded, subsequent invocations of the EJB’s methods by the client result in a NoSuchEJBException, which is a subclass of RuntimeException.§ With message-driven beans, a system exception thrown by the onMessage() method or one of the callback methods (@PostConstruct or @PreDestroy) will cause the bean instance to be discarded. If the MDB was a BMT bean, the message it was handling may or may not be redelivered, depending on when the EJB container acknowledges delivery. In the case of container-managed transactions, the container will roll back the transaction, so the message will not be acknowledged and may be redelivered.
  • #70 We want the transaction to be rolled back automatically, but business logic may be able to catch InsufficientBalanceException and retry the transaction automatically