Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Nov 30, 2004



Application Security Testing: An Integral Part of DevOps

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.
Mouli Chandra
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date