YourNote 602: Enterprise JavaBeans (EJB) - zhamri/CSC584-Enterprise_Programming GitHub Wiki
1. What is EJB?
Enterprise JavaBeans (EJB) is a server-side Java technology used to build enterprise applications.
EJB provides built-in services such as:
- Transaction management
- Security
- Dependency Injection
- Concurrency management
- Scheduling
- Messaging
- Remote access
- Distributed computing
EJB runs inside an EJB Container provided by a Jakarta EE Application Server.
Examples:
- WildFly
- GlassFish
- Payara Server
- JBoss EAP
- TomEE
2. Why was EJB created?
Before EJB, developers had to manually handle:
- Database transactions
- Security
- Object lifecycle
- Resource pooling
- Thread management
Example without EJB:
public void transferMoney() {
Connection conn = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
withdraw();
deposit();
conn.commit();
} catch (Exception e) {
conn.rollback();
}
}
EJB automates many of these tasks.
3. EJB Architecture
Client
|
v
EJB Container
|
v
Enterprise Bean
|
v
Database
The EJB Container provides:
- Transactions
- Security
- Dependency Injection
- Lifecycle Management
- Thread Management
- Connection Pooling
4. Types of EJB
There are three main types of Session Beans.
4.1 Stateless Session Bean
Most commonly used EJB.
import jakarta.ejb.Stateless;
@Stateless
public class StudentService {
public String hello() {
return "Hello Student";
}
}
Characteristics
- Does not store client state
- Reusable
- High performance
- Thread-safe
Examples
- Login service
- Student service
- Product service
- Customer service
4.2 Stateful Session Bean
Stores data for a specific client.
import jakarta.ejb.Stateful;
@Stateful
public class ShoppingCart {
private int totalItems = 0;
public void addItem() {
totalItems++;
}
public int getTotalItems() {
return totalItems;
}
}
Characteristics
- Maintains state
- One bean instance per client
- More memory usage
Examples
- Shopping cart
- Online reservation
- Multi-step form
4.3 Singleton Session Bean
Only one instance exists in the application.
import jakarta.ejb.Singleton;
@Singleton
public class SystemConfiguration {
private String version = "1.0";
public String getVersion() {
return version;
}
}
Characteristics
- Single instance
- Shared by all users
- Suitable for global data
Examples
- Application settings
- Cache management
- System configuration
5. Dependency Injection
EJB supports Dependency Injection using @EJB.
Without Dependency Injection
StudentService service = new StudentService();
With Dependency Injection
@EJB
private StudentService service;
Benefits:
- Loose coupling
- Easier maintenance
- Easier testing
6. Transactions
One of the most important EJB features.
Example:
@Stateless
public class BankService {
public void transferMoney() {
withdraw();
deposit();
}
}
If one operation fails:
Withdraw Success
Deposit Failed
Result:
Rollback Everything
Transaction management is handled automatically.
7. Transaction Attributes
EJB supports several transaction behaviors.
@TransactionAttribute(
TransactionAttributeType.REQUIRED
)
| Attribute | Description |
|---|---|
| REQUIRED | Join existing transaction or create new |
| REQUIRES_NEW | Always create new transaction |
| MANDATORY | Transaction must already exist |
| SUPPORTS | Use transaction if available |
| NOT_SUPPORTED | Execute without transaction |
| NEVER | Transaction not allowed |
8. Security
EJB supports declarative security.
@RolesAllowed("ADMIN")
public void deleteStudent() {
}
Only users with the ADMIN role can execute the method.
Common Security Annotations
@RolesAllowed
@PermitAll
@DenyAll
9. Local EJB
Used within the same application.
Interface
import jakarta.ejb.Local;
@Local
public interface StudentServiceLocal {
String getStudentName();
}
Implementation
@Stateless
public class StudentService implements StudentServiceLocal {
public String getStudentName() {
return "Ali";
}
}
Advantages
- Faster
- Same JVM
- Lower overhead
10. Remote EJB
Used across servers or applications.
Interface
import jakarta.ejb.Remote;
@Remote
public interface StudentServiceRemote {
String getStudentName();
}
Implementation
@Stateless
public class StudentService implements StudentServiceRemote {
public String getStudentName() {
return "Ali";
}
}
Advantages
- Distributed computing
- Enterprise integration
Disadvantages
- Network overhead
11. Asynchronous EJB
Execute methods in the background.
import jakarta.ejb.Asynchronous;
@Asynchronous
public void sendEmail() {
System.out.println("Sending email");
}
Examples
- Email sending
- Report generation
- Background processing
12. Timer Service
EJB provides scheduling support.
import jakarta.ejb.Schedule;
@Schedule(hour="0", minute="0")
public void backupDatabase() {
}
Runs every day at midnight.
Examples
- Database backup
- Daily reports
- Data synchronization
13. Message-Driven Bean (MDB)
Used for asynchronous messaging.
import jakarta.ejb.MessageDriven;
@MessageDriven
public class OrderProcessor {
}
Architecture:
Producer
|
Queue
|
MDB
|
Database
Common Message Brokers
- ActiveMQ
- RabbitMQ
- IBM MQ
Use Cases
- Order processing
- Notification systems
- Event-driven systems
14. EJB Lifecycle
Stateless Bean Lifecycle
Create
|
Ready
|
Destroy
Stateful Bean Lifecycle
Create
|
Ready
|
Passivate
|
Activate
|
Destroy
Definitions
| State | Description |
|---|---|
| Create | Bean created |
| Ready | Bean active |
| Passivate | Bean temporarily stored |
| Activate | Bean restored |
| Destroy | Bean removed |
15. Common EJB Annotations
| Annotation | Purpose |
|---|---|
| @Stateless | Stateless Bean |
| @Stateful | Stateful Bean |
| @Singleton | Singleton Bean |
| @EJB | Dependency Injection |
| @Local | Local Interface |
| @Remote | Remote Interface |
| @Asynchronous | Background Execution |
| @Schedule | Scheduler |
| @MessageDriven | Message Bean |
| @RolesAllowed | Security |
| @TransactionAttribute | Transaction Management |
16. EJB Advantages
- Simplifies enterprise development
- Automatic transaction management
- Built-in security
- Built-in scheduling
- Dependency Injection
- Distributed application support
- Scalable architecture
17. EJB Disadvantages
- Requires application server
- More complex than Spring Boot
- Higher memory consumption
- Slower startup time
- Less popular for new projects
18. EJB vs Spring Boot
| Feature | EJB | Spring Boot |
|---|---|---|
| Container | Application Server | Embedded Server |
| Deployment | WAR / EAR | Executable JAR |
| Learning Curve | Higher | Easier |
| Startup Time | Slower | Faster |
| Microservices | Limited | Excellent |
| Cloud Support | Moderate | Excellent |
| Popularity Today | Lower | Very High |
19. Typical Enterprise Application Using EJB
Web Application
|
v
EJB Layer
|
v
JPA Layer
|
v
Database
Example:
StudentController
|
StudentEJB
|
StudentRepository
|
PostgreSQL
Summary
EJB is a Jakarta EE technology for building enterprise applications.
Core concepts to master:
- Stateless Session Bean
- Stateful Session Bean
- Singleton Session Bean
- Dependency Injection
- Transaction Management
- Security
- Local and Remote EJB
- Message-Driven Bean
- Timer Service
- EJB Lifecycle
Although Spring Boot is more popular for new projects today, understanding EJB is important because many enterprise systems in banks, insurance companies, government agencies, and large organizations still use EJB-based architectures.