我创建了一个SampleEntityBean,homeInterface,componentInterface和客户端类。 我想要做的就是访问SampleEntityBean(doCalculation)中定义的方法。 EntityBean代码是。
public class SampleEntityBean implements EntityBean{
@Id
@TableGenerator(name= " ")
@Column()
Integer key;
public Integer getID(){
return key;
}
public Integer doCalculation(Integer inputs){
return inputs*2;
}
/**
* Default constructor.
*/
public SampleEntityBean() {
// TODO Auto-generated constructor stub
}
@Override
public void ejbActivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
@Override
public void ejbLoad() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
@Override
public void ejbPassivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
@Override
public void ejbRemove() throws RemoveException, EJBException, RemoteException {
// TODO Auto-generated method stub
}
@Override
public void ejbStore() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
@Override
public void setEntityContext(EntityContext arg0) throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
@Override
public void unsetEntityContext() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
}
和homeInterface是:
package sampleEntitybean;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
import sampleEntitybean.SampleEntityBean;
public interface homeInterface extends EJBHome{
public SampleEntityBean create()throws CreateException,RemoteException;
}
和componentInterface是:
package sampleEntitybean;
public interface componentInterface extends javax.ejb.EJBLocalObject {
public Integer doCalculation(Integer inputs);
}
和客户端是:
package sampleEntitybean;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ApplicationClient {
public static void main(String[] args) throws NamingException, RemoteException, CreateException {
// TODO Auto-generated method stub
Context initial = new InitialContext();
Context environment = (Context)initial.lookup("java:comp/env");
homeInterface home = (homeInterface)initial.lookup("SampleEntityBean");
SampleEntityBean bean = home.create();
int a = bean.doCalculation(10);
System.out.println(a);
}
}
我得到的错误是:
Exception in thread "main" 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 sampleEntitybean.ApplicationClient.main(ApplicationClient.java:15)