每个bean可能会有很多方法,一般我们通过一个delegate来调用sessionbean中的方法,而非直接调用sessionbean,delegate中只是简单的对每个相对应的sessionbean的public方法的简单封装,在调用的时候省去了每次对home的查找和ejb对象的create,但是可能我们的bean会有很多方法,如果每个bean都写这样一个delegate,这样工作量就会很大,而且也不便于以后系统的移植,比如说,原来使用ejb实现,现在要改用jdo直接操作数据库,而通过运用java的reflect技术,就能较好地实现这些要求。首先,定义了一个FacadeDelegate的抽象类,用来实现对sessionbean的home的查找,代码如下:
import javax.ejb.*;
import testejb.util.common.*;
import testejb.util.resource.*;
public abstract class FacadeDelegate{
private static String type = Resource.RemoteType;
public FacadeDelegate() {
}
public EJBHome getHome(String jindiName,Class className)
{
EJBHome home = null;
ServerLocatorAdapter adapter = ServerLocatorAdapter.getInstance();
try
{
home = (EJBHome)adapter.getHome(type, jindiName, className);
}
catch(Exception e)
{
System.err.println(e.getMessage() + jindiName + className.toString());
}
return home;
}
}
其中ServerLocatorAdapter是一个用来根据是local还是remote调用ejb对象而通过不同的方法查找home的类,如果type为local则调用LocalServerLocate中的方法,如果type为remote则调用RemoteServerLocate中的方法,获得home。代码如下:
import java.util.*;
import java.lang.reflect.*;
import testejb.util.resource.*;
public class ServerLocatorAdapter {
private Map cache;//用来缓存home
private static ServerLocatorAdapter me;
public static ServerLocatorAdapter getInstance()
{
if(me == null)
me = new ServerLocatorAdapter();
return me;
}
//取得home
public Object getHome(String type,String jndiHomeName,Class className) throws Exception
{
Object home = null;
if(cache.containsKey(jndiHomeName))
return cache.get(jndiHomeName);
if(Resource.LocalType.equals(type))
{
home = getLocalHome(jndiHomeName,className);
cache.put(jndiHomeName,home);
return home;
}
if(Resource.RemoteType.equals(type))
{
home = getRemoteHome(jndiHomeName,className);
cache.put(jndiHomeName,home);
return home;
}
return home;
}
//取得local home
private Object getLocalHome(String jndiHomeName,Class className) throws Exception
{
Class myClass = Class.forName(Resource.LocalClass);
// Resource. LocalClass =”testejb.util.common. LocalServerLocator
Method method = myClass.getMethod(Resource.LocalConstractMethod,null);
// Resource. LocalConstractMethod =” getInstance”
LocalServerLocator local = null;
local = (LocalServerLocator)method.invoke(myClass,null);
return local.getLocalHome(jndiHomeName,className);
}
//取得remote home
private Object getRemoteHome(String jndiHomeName,Class className) throws Exception
{
Class myClass = Class.forName(Resource.RemoteClass);
// Resource.RemoteClass =”testejb.util.common.RemoteServerLocator”
Method method = myClass.getMethod(Resource.RemoteConstractMethod,null);
// Resource.RemoteConstractMethod=” getInstance”
RemoteServerLocator remote = null;
remote = (RemoteServerLocator)method.invoke(myClass,null);
return remote.getHome(jndiHomeName,className);
}
private ServerLocatorAdapter() {
// 为cache提供线程安全的保证
cache = Collections.synchronizedMap(new HashMap());
}
}