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) { } } }