對於遠程查找
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
static String url = "corbaloc:iiop:localhost:2809";
static String initial = "com.ibm.websphere.naming.WsnInitialContextFactory";
static String jndi = "ejb/enterprise_app_name/ejb_web_project_name.jar/ejb_name#name.of.remote.impl.interface";
private static ServiceLocator serviceLocator = null;
InitialContext context = null;
private ServiceLocator() throws NamingException, IOException {
Hashtable<String,String> env = new Hashtable<String,String>();
env.put("java.naming.provider.url", url);
env.put("java.naming.factory.initial", initial);
context = new InitialContext(env);
}
public synchronized static ServiceLocator getInstance() throws NamingException, IOException {
if (serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public Object getService(String jndiName) throws NamingException {
return context.lookup(jndiName);
}
public <T>T getRemoteObject(Class<T> remoteInterfaceClass) {
try {
return (T)javax.rmi.PortableRemoteObject.narrow(context.lookup(jndi), remoteInterfaceClass);
} catch (NamingException nexc) {
nexc.printStackTrace();
}
return null;
}
}
對於本地查找
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
static String url = "iiop://localhost";
static String initial = "com.ibm.websphere.naming.WsnInitialContextFactory";
static String jndi = "ejblocal:enterprise_app_name/ejb_web_project_name.jar/ejb_name#name.of.local.impl.interface";
private static ServiceLocator serviceLocator = null;
InitialContext context = null;
private ServiceLocator() throws NamingException, IOException {
Hashtable<String,String> env = new Hashtable<String,String>();
env.put("java.naming.provider.url", url);
env.put("java.naming.factory.initial", initial);
context = new InitialContext(env);
}
public synchronized static ServiceLocator getInstance() throws NamingException, IOException {
if (serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public Object getService(String jndiName) throws NamingException {
return context.lookup(jndiName);
}
public Object getService() throws NamingException {
return context.lookup(jndi);
}
}
它的工作就像一個魔法。你可以給一些參考讀物的一些指示,以瞭解更多關於此? – Rafi
我已添加信息中心鏈接,但如果您有其他問題,請告知我。 –