Everything You Need to Know About Enterprise JavaBeans (EJB): Features, Types, and RMI
Enterprise JavaBeans (EJB) Mechanism
Everything You Need to Know About Enterprise JavaBeans (EJB): Features, Types, and RMI
Enterprise JavaBeans (EJB) Mechanism
- Introduction to EJB Enterprise JavaBeans (EJB) is a server-side component architecture used to build scalable, distributed, and secure Java applications. It simplifies enterprise-level development by providing built-in support for transactions, security, and remote communication.
Key Features of EJB:
- Centralized business logic
- Built-in transaction management
- Declarative security
- Remote method invocation (RMI)
- Scalability and performance via instance pooling
Types of EJB: EJB consists of three primary types:
- Stateless Session Beans
- Stateful Session Beans
- Message-Driven Beans (MDBs)
2. Exposing Java API Using EJB EJB can expose APIs to clients in multiple ways, such as:
- Remote Interface: Clients invoke methods remotely via RMI, providing distributed access.
- Local Interface: For same-application communication, bypassing RMI for efficiency.
- Message-Driven Beans: Process asynchronous messages using JMS.
Example: Remote Interface
- Remote Interface:
import javax.ejb.Remote;
@Remote
public interface CalculatorRemote {
int add(int a, int b);
int subtract(int a, int b);
}
2. Bean Implementation:
import javax.ejb.Stateless;
@Stateless
public class CalculatorBean implements CalculatorRemote {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int subtract(int a, int b) {
return a - b;
}
}
3. Client Code:
import javax.naming.Context;
import javax.naming.InitialContext;
public class Client {
public static void main(String[] args) throws Exception {
Context context = new InitialContext();
CalculatorRemote calculator = (CalculatorRemote) context.lookup("java:global/MyApp/CalculatorBean");
System.out.println("Addition: " + calculator.add(10, 20));
System.out.println("Subtraction: " + calculator.subtract(20, 10));
}
}
3. Remote Method Invocation (RMI) in EJB RMI is essential for distributed communication in EJB. It allows clients to invoke methods on remote objects (EJBs) running on the server.
How RMI Works in EJB:
- Proxy Object Creation: A proxy object implementing the remote interface is created on the client side.
- Method Invocation: The client calls a method on the proxy.
- Serialization: The proxy serializes the method call and sends it to the server.
- Execution and Response: The container invokes the method on the bean and sends the result back to the client.
Components Deployed on the Client:
- Only the remote interface and any dependent DTOs (Data Transfer Objects).
- The actual bean (business logic) resides on the server.
Why Not Deploy Bean on Client?
- Centralized logic and easier updates
- Container-managed transactions and security
- Efficient resource management
4. Lifecycle of EJB and Instance Pooling The lifecycle of EJB involves several phases, managed by the container.
For Stateless Session Beans:
- Pool Creation:
- The container initializes a pool of bean instances when the application is deployed.
- The pool size can be configured (e.g., minimum and maximum).
2. Instance Usage:
- When a client request arrives, the container picks an instance from the pool to handle the request.
- After processing, the instance is returned to the pool.
3. Instance Destruction:
- Unused instances may be destroyed to free resources.
- The
@PreDestroylifecycle method is invoked before destruction.
Example Configuration for Pooling:
- WildFly:
<stateless>
<pool>
<strict-max-pool max-pool-size="20" timeout="5"/>
</pool>
</stateless>
For Stateful Session Beans:
- Each client gets its own instance.
- State is maintained between method calls.
Example:
- Stateful Bean Interface:
import javax.ejb.Remote;
@Remote
public interface ShoppingCartRemote {
void addItem(String item);
void removeItem(String item);
List<String> getItems();
}
2. Bean Implementation:
import javax.ejb.Stateful;
import java.util.ArrayList;
import java.util.List;
@Stateful
public class ShoppingCartBean implements ShoppingCartRemote {
private List<String> items = new ArrayList<>();
@Override
public void addItem(String item) {
items.add(item);
}
@Override
public void removeItem(String item) {
items.remove(item);
}
@Override
public List<String> getItems() {
return items;
}
}
3. Client Code:
import javax.naming.Context;
import javax.naming.InitialContext;
public class ShoppingCartClient {
public static void main(String[] args) throws Exception {
Context context = new InitialContext();
ShoppingCartRemote cart = (ShoppingCartRemote) context.lookup("java:global/MyApp/ShoppingCartBean");
cart.addItem("Book");
cart.addItem("Pen");
System.out.println("Items: " + cart.getItems());
cart.removeItem("Pen");
System.out.println("Items after removal: " + cart.getItems());
}
}
For Message-Driven Beans:
- Instances are pooled like stateless beans but are triggered by messages.
Example: Message-Driven Bean for Calculation
- MDB Implementation:
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:/jms/queue/CalculationQueue")
})
public class CalculationMDB implements MessageListener {
@Override
public void onMessage(Message message) {
try {
String operation = message.getBody(String.class);
String[] parts = operation.split(",");
String type = parts[0];
int a = Integer.parseInt(parts[1]);
int b = Integer.parseInt(parts[2]);
int result = switch (type) {
case "add" -> a + b;
case "subtract" -> a - b;
default -> 0;
};
System.out.println("Operation: " + type + ", Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. Sending a Message to the Queue:
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
public class CalculationSender {
public static void main(String[] args) throws Exception {
Context context = new InitialContext();
ConnectionFactory factory = (ConnectionFactory) context.lookup("java:/ConnectionFactory");
Queue queue = (Queue) context.lookup("java:/jms/queue/CalculationQueue");
try (Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) {
String operation = "add,10,20"; // Example: "add,10,20" or "subtract,30,15"
TextMessage message = session.createTextMessage(operation);
session.createProducer(queue).send(message);
System.out.println("Message sent: " + operation);
}
}
}
5. Advantages of EJB Mechanism
Simplified Development:
- Developers focus on business logic while the container handles infrastructure.
Built-in Services:
- Transaction management, security, concurrency, and remote communication.
Scalability:
- Instance pooling optimizes resource utilization.
Centralized Business Logic:
- Simplifies updates and enforces consistent logic.
6. Summary
- Types of EJB: Stateless, Stateful, and Message-Driven Beans.
- Core Features: Transactions, security, RMI, and pooling.
- Instance Pooling: Efficient management for stateless and message-driven beans.
- Remote Communication: Achieved via RMI and proxy objects.
EJB is a robust framework for enterprise applications, providing a solid foundation for building scalable and secure solutions.
메타데이터
- post_id
- 9c8da700e86a
- slug
- everything-you-need-to-know-about-enterprise-javabeans-ejb-features-types-and-rmi-9c8da700e86a
- url
- https://medium.com/@upadhyay068/everything-you-need-to-know-about-enterprise-javabeans-ejb-features-types-and-rmi-9c8da700e86a
- canonical_url
- https://medium.com/@upadhyay068/everything-you-need-to-know-about-enterprise-javabeans-ejb-features-types-and-rmi-9c8da700e86a
- author_url
- https://medium.com/@upadhyay068
- status
- ok
- fetched_at
- 2026-06-26 21:52:29