| 類型 | 狀態保持 | 適用場景 | 生命週期 |
|---|---|---|---|
| Stateful | 跨方法調用保持會話狀態 | 購物車、ATM 連續操作、多步驟精靈 | 客戶端建立 → 移除/逾時銷毀 |
| Stateless | 無會話狀態,單次業務邏輯 | 密碼驗證、查詢服務、無狀態業務處理 | 容器管理池化,按需分配/回收 |
create(), find(), remove())EJBObject)SessionBean,容器回調方法public class MyBean implements SessionBean {
private SessionContext ctx;
// 1. 註入容器上下文
public void setSessionContext(SessionContext ctx) { this.ctx = ctx; }
// 2. 初始化(可多載參數)
public void ejbCreate() { ... }
public void ejbCreate(String param) { ... }
// 3. 被動化:釋放資源前持久化狀態
public void ejbPassivate() { ... }
// 4. 活化:還原狀態
public void ejbActivate() { ... }
// 5. 移除清理
public void ejbRemove() { ... }
// 業務方法
public String showname() { return "Hello"; }
}
// Home
public interface MyBeanHome extends EJBHome {
MyBeanRemote create() throws RemoteException, CreateException;
}
// Remote
public interface MyBeanRemote extends EJBObject {
String showname() throws RemoteException;
}
Context ctx = new InitialContext();
Object ref = ctx.lookup("MyBean"); // JNDI 定位 Home
MyBeanHome home = (MyBeanHome) PortableRemoteObject.narrow(ref, MyBeanHome.class);
MyBeanRemote remote = home.create(); // 建立 EJBObject 代理
String result = remote.showname(); // 呼叫業務方法
Win2000 + JBuilder 5/6 + BES 4.5 測試通過。