一,定义有状态Bean和无状态Bean
有状态Bean:
@Stateful @Remote public class StatefulEjbBean implements StatefulEjb{ private int state; @Override public void compute(int i) { state=state+i; } @Override public int getResult() { return state; } }
无状态Bean:
@Stateless @Remote public class StatelessEjbBean implements StatelessEjb { private int state; @Override public void compute(int i) { state = state + i; } @Override public int getResult() { return state; } }
二,客户端测试及结果
1,测试有状态EJB对象:
public class StatefulEjbClient { public static void main(String[] args) throws Exception { InitialContext context=new InitialContext(); //第一次会话 StatefulEjb ejb1=(StatefulEjb)context.lookup("StatefulEjbBean/remote"); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); System.out.println("第一次会话结束---------"); //第二次会话 StatefulEjb ejb2=(StatefulEjb)context.lookup("StatefulEjbBean/remote"); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); System.out.println("第二次会话结束---------"); } }
结果:
2,测试无状态EJB对象:
public class StatelessEjbClient { public static void main(String[] args) throws NamingException { InitialContext context=new InitialContext(); //第一次会话 StatelessEjb ejb1=(StatelessEjb)context.lookup("StatelessEjbBean/remote"); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); ejb1.compute(1); System.out.println(ejb1.getResult()); System.out.println("第一次会话结束---------"); //第二次会话 StatelessEjb ejb2=(StatelessEjb)context.lookup("StatelessEjbBean/remote"); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); ejb2.compute(1); System.out.println(ejb2.getResult()); System.out.println("第二次会话结束---------"); //判断每次查找到的对象是否一样 System.out.println(ejb1==ejb2);//false } }
结果:
三,结果对比
通过多次执行,发现对于有状态的EJB对象,每次通过查找获得的对象都是新对象;而对于无状态的EJB对象,每次查找获得的对象都有一个单例类的效果,多次执行测试无状态的EJB对象的方法,会发现服务端的貌似始终在对一个对象进行操作。
时间: 2024-10-28 05:36:26