圖B EJB訪問的靈活性讓你能夠運用合成原理利用多個JavaBeans和一個或者多個POJO創建邏輯組件。讓我們看一個簡單的EJB應用程序吧,這個程序用一個事務方法公開了一個用戶帳號。JavaBean這個賬號的遠程接口看起來會像Listing A里的一樣。那么事務邏輯類就會看起來像Listing B里的一樣。最后,客戶端的代碼會像Listing C里的這樣。 Listing A
public interface Account extends javax.ejb.EJBObject, java.rmi.Remote { public String getBalance() throws java.rmi.RemoteException; } Our home interface might look something like the following: public interface AccountHome extends javax.ejb.EJBHome { public Account create() throws javax.ejb.CreateException, java.rmi.RemoteException; }
Listing B
public class AccountBean implements javax.ejb.sessionBean { PRivate javax.ejb.SessionContext ctx; public void ejbActivate() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbPassivate() {} public void setSessionContext(javax.ejb.SessionContext ctx) { this.ctx = ctx; } // business method public String getBalance() throws java.rmi.RemoteException { String balance = accessDataTierAccount(); return(balance); } }
Listing C
public class AccountClient { public String getAccountBalance() { try { javax.naming.Context ctx = getInitialContext(); AccountHome home = (AccountHome)ctx.lookup("Bank.AccountHome"); Account account = home.create(); account.getBalance(); } catch(Exception e) { } } }