📄 remotefactory.java
字号:
package lee;
import java.util.Map;
import java.util.HashMap;
import javax.ejb.EJBObject;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.ejb.CreateException;
import java.rmi.RemoteException;
/**
* @author yeeku.H.lee kongyeeku@163.com
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class RemoteFactory
{
private static RemoteFactory instance;
//用这个HashMap来缓存查找到的EJBRemote
private Map remoteInterfaces;
private Context context;
private RemoteFactory() throws NamingException
{
remoteInterfaces = new HashMap();
context = getInitialContext();
}
public static synchronized RemoteFactory getInstance() throws NamingException
{
//不是线程安全的,但已经足够 || 加上synchronized会变成线程安全,但性能会下降
if (instance == null)
{
instance = new RemoteFactory();
}
return instance;
}
private EJBObject lookup(String jndiName, Class homeInterfaceClass)
throws NamingException,CreateException,RemoteException
{
EJBObject remoteInterface = null;
remoteInterface = (EJBObject)remoteInterfaces.get(homeInterfaceClass);
//如果该接口不存在,则执行JNDI查找
if (remoteInterface == null)
{
Object obj = context.lookup(jndiName);
MyEJBHome homeInterface = (MyEJBHome)PortableRemoteObject.narrow(obj, homeInterfaceClass);
remoteInterface = homeInterface.create();
//如果这是个新的引用对象,则将该对象保存入缓存
remoteInterfaces.put(homeInterfaceClass, remoteInterface);
}
return remoteInterface;
}
//避免每次都重新初始化Context
private Context getInitialContext()
{
if (context == null)
{
//如果不是在J2EE程序里,还需要属性文件才能正确查找到InitialConext()
try
{
context = new InitialContext();
}
catch (NamingException ne)
{
ne.printStackTrace();
}
}
return context;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -