Enterprise JavaBeans (EJB)
1. What is EJB?
EJB is Java EE's server-side component architecture for building distributed, transactional, secure, scalable business applications. An EJB runs inside an EJB container (part of an application server — WebLogic, WebSphere, JBoss/WildFly, GlassFish) which supplies the "plumbing": transactions, security, persistence, concurrency, remoting, pooling.
CLIENT (browser / another EJB / RMI client)
|
v
+------------------------- APPLICATION SERVER --------------------------+
| +------------------ EJB CONTAINER ---------------------------------+ |
| | Session beans | Entity beans | Message-driven beans | |
| | (business) | (persistence)| (async messaging) | |
| +-----------------------------------------------------------------+ |
| Services: JTA transactions, security (roles), pooling, persistence, |
| concurrency, timers, RMI/IIOP remoting, dependency injection |
+-----------------------------------------------------------------------+
2. Types of EJBs
| Type | Purpose | Life |
|---|---|---|
| Session bean — Stateless | Business logic with no client state between calls (e.g. calculateTax, creditAccount); pooled and shared |
Short — lives per method call |
| Session bean — Stateful | Keeps conversational state for one client (e.g. a shopping cart); passivated/activated by the container | Long — one per client session |
| Session bean — Singleton | One instance per application; shared state, start-up/scheduled jobs (EJB 3.1+) | Application life |
| Entity bean (EJB 2.x; deprecated in 3.x in favour of JPA) | Persistent business data mapped to DB rows | Persistent |
| Message-driven bean (MDB) | Asynchronous consumer of JMS messages — no client interface | Per message |
3. EJB 3.x Style (annotation-driven — the modern way)
@Stateless
public class AccountServiceBean implements AccountService {
@Resource private DataSource ds; // injected by container
@PersistenceContext private EntityManager em; // JPA
public double withdraw(String acct, double amt) {
Account a = em.find(Account.class, acct);
if (a.getBalance() < amt) throw new InsufficientFundsException();
a.setBalance(a.getBalance() - amt);
return a.getBalance(); // container commits the TX
}
}
Deployment descriptor (ejb-jar.xml) now optional — annotations (@Stateless, @Stateful, @Singleton, @MessageDriven, @TransactionAttribute, @RolesAllowed, @Schedule) replace most XML.
4. Container Services (what the container gives you)
- Transaction management — declarative:
@TransactionAttribute(REQUIRED | REQUIRES_NEW | MANDATORY | SUPPORTS | NOT_SUPPORTED | NEVER); container commits/rolls back automatically (CMT) or the bean manages it (BMT). - Security — declarative role-based access:
@RolesAllowed("admin"),@PermitAll, principal propagation from the login. - Persistence — CMP (container-managed) or BMP; in EJB 3, JPA
@Entityclasses with EntityManager. - Concurrency & pooling — instance pools, passivation of stateful beans, locking for singletons (
@Lock(READ/WRITE)). - Life-cycle callbacks —
@PostConstruct,@PreDestroy,@PostActivate,@PrePassivate. - Remoting / invocation — local (
@Local) vs remote (@Remote) business interfaces; RMI-IIOP or web-service endpoints. - Timer service —
@Schedule(cron = "0 0 2 * * ?")for scheduled jobs.
5. Session Bean Life Cycle (stateless example)
Does not exist -> newInstance() -> dependency injection (@Resource/@EJB)
-> @PostConstruct -> business method calls (pooled)
-> @PreDestroy -> end of life
Stateful beans additionally: passivation (serialize to disk when inactive) and activation when the client returns.
6. Client View
@EJB AccountService service; // inside another managed bean
// or remote lookup:
Context ctx = new InitialContext();
AccountService s = (AccountService) ctx.lookup("java:global/bank/AccountServiceBean");
7. Advantages and Limitations
Advantages
- Container handles the hard enterprise plumbing (transactions, security, persistence, concurrency) — developer writes only business logic.
- Portability across compliant app servers; scalability via pooling/clustering; declarative style keeps code clean.
- Standard, mature ecosystem, integrates with JPA, JMS, JTA, CDI.
Limitations
- Heavyweight infrastructure — full application server; complex debugging; deployment overhead for small apps.
- Historical "EJB 2.x complexity" (home/remote interfaces, XML) gave it a bad reputation; EJB 3 fixed much of it.
- Remote calls add latency; learning curve remains significant. Many modern teams use Spring Boot or microservices instead.
8. Exam Points
- Explain the EJB architecture and container services with a diagram — 10 marks (very frequent).
- Differentiate stateless, stateful, singleton session beans and MDB — 5-7 marks.
- Declarative transaction and security attributes with examples — 5 marks.
- Life cycle of a stateless / stateful bean (passivation/activation) — 5-7 marks.
- Compare EJB with CORBA/DCOM — 5 marks.