清單 1. 典型的 EJB 查找 public boolean buyItems(PaymentInfo paymentInfo, String storeName, List items) { // Load up the initial context Context ctx = new InitialContext();
// Look up a bean's home interface Object obj = ctx.lookup("java:comp/env/ejb/PurchaseHome"); PurchaseHome purchaseHome = (PurchaseHome)PortableRemoteObject.narrow(obj, PurchaseHome.class); Purchase purchase = purchaseHome.create(paymentInfo);
// Work on the bean for (Iterator i = items.iterator(); i.hasNext(); ) { purchase.addItem((Item)i.next()); }
// Look up another bean Object obj = ctx.lookup("java:comp/env/ejb/InventoryHome"); InventoryHome inventoryHome = (InventoryHome)PortableRemoteObject.narrow(obj, InventoryHome.class); Inventory inventory = inventoryHome.findByStoreName(storeName);
// Work on the bean for (Iterator i = items.iterator(); i.hasNext(); ) inventory.markAsSold((Item)i.next()); }
// This is private, and can't be instantiated directly private EJBHomeFactory() throws NamingException { homeInterfaces = new HashMap();
// Get the context for caching purposes context = new InitialContext();
/** * In non-J2EE applications, you might need to load up * a properties file and get this context manually. I've * kept this simple for demonstration purposes. */ }
public static EJBHomeFactory getInstance() throws NamingException { // Not completely thread-safe, but good enough // (see note in article) if (instance == null) { instance = new EJBHomeFactory(); } return instance; }
public EJBHome lookup(String jndiName, Class homeInterfaceClass) throws NamingException {
// See if we already have this interface cached EJBHome homeInterface = (EJBHome)homeInterfaces.get(homeClass);
// If not, look up with the supplied JNDI name if (homeInterface == null) { Object obj = context.lookup(jndiName); homeInterface = (EJBHome)PortableRemoteObject.narrow(obj, homeInterfaceClass);
// If this is a new ref, save for caching purposes homeInterfaces.put(homeInterfaceClass, homeInterface); } return homeInterface; } }
EJBHomeFactory 類內幕 home 接口工廠的要害在 homeInterfaces 映射中。該映射存儲了供使用的每個 bean 的 home 接口;這樣,home 接口實例可以反復使用。您還應注重,映射中的要害并不是傳遞到 lookup() 方法的 JNDI 名稱。將同一 home 接口綁定到不同 JNDI 名稱是很常見的,但這樣做會在您的映射中產生副本。通過依靠類本身,您就可以確保最終不會為同一個 bean 創建多個 home 接口。
將新的 home 接口工廠類插入清單 1 的原始代碼,這樣將會產生優化的 EJB 查找,如清單 4 所示:
清單 4. 改進的 EJB 查找 public boolean buyItems(PaymentInfo paymentInfo, String storeName, List items) {