上面为一个有问题的EJB,能力有限现在还不知道问题所在。不过我又写了一个能运行成功的,本人初学EJB对其理解有限,下面只是把具体的代码和我觉得需要注意的地方写下来
我使用的是Myeclipse和weblogic,EJB的版本是3.0
首先下面是EJB工程的目录结构及代码:
package com.earth;
public class Employee implements java.io.Serializable
{
private String name;
private String
job;
private int age;
public String getName()
{
return name;
}
public void setName(String
name) {
this.name = name;
}
public String
getJob() {
return job;
}
public void
setJob(String job) {
this.job = job;
}
public
int getAge() {
return age;
}
public void
setAge(int age) {
this.age = age;
};
}
package com.earth;
import javax.ejb.Remote;
@Remote
public interface CompanyRemote {
public String
getName();
public Employee[] getEmployees();
}
package com.earth;
import javax.ejb.Stateless;
@Stateless(mappedName="Company")
public class Company implements
CompanyRemote {
@Override
public String getName() {
return
"xianyuyuyuyuyuyu";
}
@Override
public Employee[] getEmployees()
{
Employee[] employees = new
Employee[2];
employees[0] = new
Employee();
employees[0].setName("superman");
employees[0].setJob("CEO");
employees[0].setAge(1234);
employees[1]
= new
Employee();
employees[1].setName("xianyu");
employees[1].setJob("CTO");
employees[1].setAge(4321);
return
employees;
}
}
下面是测试用的代码,当然测试用的代码是写在另外一个java工程里
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import
javax.naming.NamingException;
import com.earth.*;
public class TestCompany {
/**
* @param args
*/
public static void
main(String[] args) {
String url =
"t3://localhost:7001";
Properties p = new
Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL,
url);
InitialContext ctx;
try
{
ctx = new
InitialContext(p);
CompanyRemote companyRemote
=(CompanyRemote)ctx.lookup("Company#com.earth.CompanyRemote");
System.out.println(companyRemote.getName());
Employee[]
employees = companyRemote.getEmployees();
for(Employee employee :
employees){
System.out.println("name:"+employee.getName());
System.out.println("job:"+employee.getJob());
System.out.println("age:"+employee.getAge());
System.out.println("----------------------");
}
}
catch (NamingException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
}
}
我是直接用Myeclipse发布的,当然你们也可以手动发布这里我就不多少了。
我们需要通过JNDI来得到对象,下面是查询JNDI名的界面,而JNDI的详解我就不说了。
下面附上结果: