-
Notifications
You must be signed in to change notification settings - Fork 0
YourNote 602: Enterprise JavaBeans (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
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.
Client
|
v
EJB Container
|
v
Enterprise Bean
|
v
Database
The EJB Container provides:
- Transactions
- Security
- Dependency Injection
- Lifecycle Management
- Thread Management
- Connection Pooling
There are three main types of Session Beans.
Most commonly used EJB.
import jakarta.ejb.Stateless;
@Stateless
public class StudentService {
public String hello() {
return "Hello Student";
}
}- Does not store client state
- Reusable
- High performance
- Thread-safe
- Login service
- Student service
- Product service
- Customer service
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;
}
}- Maintains state
- One bean instance per client
- More memory usage
- Shopping cart
- Online reservation
- Multi-step form
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;
}
}- Single instance
- Shared by all users
- Suitable for global data
- Application settings
- Cache management
- System configuration
EJB supports Dependency Injection using @EJB.
StudentService service = new StudentService();@EJB
private StudentService service;Benefits:
- Loose coupling
- Easier maintenance
- Easier testing
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.
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 |
EJB supports declarative security.
@RolesAllowed("ADMIN")
public void deleteStudent() {
}Only users with the ADMIN role can execute the method.
@RolesAllowed@PermitAll@DenyAllUsed within the same application.
import jakarta.ejb.Local;
@Local
public interface StudentServiceLocal {
String getStudentName();
}@Stateless
public class StudentService implements StudentServiceLocal {
public String getStudentName() {
return "Ali";
}
}- Faster
- Same JVM
- Lower overhead
Used across servers or applications.
import jakarta.ejb.Remote;
@Remote
public interface StudentServiceRemote {
String getStudentName();
}@Stateless
public class StudentService implements StudentServiceRemote {
public String getStudentName() {
return "Ali";
}
}- Distributed computing
- Enterprise integration
- Network overhead
Execute methods in the background.
import jakarta.ejb.Asynchronous;
@Asynchronous
public void sendEmail() {
System.out.println("Sending email");
}- Email sending
- Report generation
- Background processing
EJB provides scheduling support.
import jakarta.ejb.Schedule;
@Schedule(hour="0", minute="0")
public void backupDatabase() {
}Runs every day at midnight.
- Database backup
- Daily reports
- Data synchronization
Used for asynchronous messaging.
import jakarta.ejb.MessageDriven;
@MessageDriven
public class OrderProcessor {
}Architecture:
Producer
|
Queue
|
MDB
|
Database
- ActiveMQ
- RabbitMQ
- IBM MQ
- Order processing
- Notification systems
- Event-driven systems
Create
|
Ready
|
Destroy
Create
|
Ready
|
Passivate
|
Activate
|
Destroy
| State | Description |
|---|---|
| Create | Bean created |
| Ready | Bean active |
| Passivate | Bean temporarily stored |
| Activate | Bean restored |
| Destroy | Bean removed |
| 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 |
- Simplifies enterprise development
- Automatic transaction management
- Built-in security
- Built-in scheduling
- Dependency Injection
- Distributed application support
- Scalable architecture
- Requires application server
- More complex than Spring Boot
- Higher memory consumption
- Slower startup time
- Less popular for new projects
| 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 |
Web Application
|
v
EJB Layer
|
v
JPA Layer
|
v
Database
Example:
StudentController
|
StudentEJB
|
StudentRepository
|
PostgreSQL
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.