我使用 eclipse 创建了一个 EJB 项目,并创建了如下 2 个类。
package com.abhijit.ejbs;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface TestEJBRemote {
public void addElement(int a);
public void removeElement(int a);
public List getElements();
}
实际的 EJB 如下 -
package com.abhijit.ejbs;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
/**
* Session Bean implementation class TesEJB
*/
@Stateful
@LocalBean
public class TestEJB implements TestEJBRemote {
List <Integer> myList = new ArrayList<>();
/**
* Default constructor.
*/
public TestEJB() {
// TODO Auto-generated constructor stub
}
@Override
public void addElement(int a) {
myList.add(a);
}
@Override
public void removeElement(int a) {
myList.remove(a);
}
@Override
public List getElements() {
return myList;
}
}
然后将此 EJB 部署在 JBoss AS 7 上,它运行时没有任何错误。我在控制台中看到此消息 -
**java:global/EJB1/TestEJB!com.abhijit.ejbs.TestEJBRemote
java:app/EJB1/TestEJB!com.abhijit.ejbs.TestEJBRemote
java:module/TestEJB!com.abhijit.ejbs.TestEJBRemote
java:jboss/exported/EJB1/TestEJB!com.abhijit.ejbs.TestEJBRemote
java:global/EJB1/TestEJB!com.abhijit.ejbs.TestEJB
java:app/EJB1/TestEJB!com.abhijit.ejbs.TestEJB
java:module/TestEJB!com.abhijit.ejbs.TestEJB**
现在,我正在创建第二个 Eclipse Java 项目并编写一个简单的 Java 远程客户端代码,如下所示——
package com;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.abhijit.ejbs.TestEJB;
import com.abhijit.ejbs.TestEJBRemote;
public class EJBClient {
public static void main(String[] args) {
TestEJBRemote values;
try {
System.out.println("----");
final Hashtable<String, String> jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
//tried with rmi: also .. not working....
jndiProperties.put(Context.PROVIDER_URL, "ejb://localhost:1099");
InitialContext ic = new InitialContext(jndiProperties);
values = (TestEJBRemote)ic.lookup("java:global/EJB1/TestEJB!com.abhijit.ejbs.TestEJB");
System.out.println("---" + values.getElements());
}
catch(Exception e) {
e.printStackTrace();
}
}
在 lookup() 中尝试了各种组合,但是当我运行这个将在单独的 JVM 中运行的 java 客户端代码时,它不起作用..我收到这个错误 -
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.EJBClient.main(EJBClient.java:25)
我确信它一定与 jndi 参数有关..但我不明白它是什么......