清单 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) {