Use the “Service Locator” Design Pattern with the J2EE Architechture

Use the “Service Locator” Design Pattern with the J2EE Architechture

This tip is an extension of a Design Pattern called “Service Locator” for the J2EE architecture. Generally, the “Service Locator” pattern returns a home object by merely accepting a string, usually a mapping for a JNDI name.

This tip creates a pure factory for stateless session beans (a method which accepts a string?in JNDI, the name of the stateless session bean) and returns the appropriate remote objects (called EJBObject) without actually type-casting the appropriate home object (called EJBHome) or executing the create method. The following code demonstrates:

Accounts valAccounts= ((AccountsHome)home).create();

This easiest way to call a subclass method without actually type-casting it is by using reflection:

Method m = homeBase.getMethod("create", null);remoteObject = (EJBObject) m.invoke(home, null);

Here’s the sample code:

/* Sample code */public class ResourceLocator{   public static EJBObect getResourceInstance(String jndiName)   {      Context ctx = new InitialContext();      Object o = ctx.lookup(jndiName);      //Need not type cast home object to appropriate Home Interface      home = (EJBHome) PortableRemoteObject.narrow(o, Class.forName("javax.ejb.EJBHome"));    //Need not type cast home object to appropriate Remote Interface    Class homeBase = home.getClass();    Method m = homeBase.getMethod("create", null);    remoteObject = (EJBObject) m.invoke(home, null);    return remoteObject;   }}

Whichever JNDI name is provided, the above code generalizes and achieves a perfect factory pattern for a stateless session bean.

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist