public class Test1(){
public vod method1(){
try{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, EJB_JNDI_FACTORY);
env.put(Context.PROVIDER_URL, EJB_URL);
InitialContext ctx = new InitialContext(env);
LogSearchRemote logSearchRemote = (LogSearchRemote) ctx.lookup(LOG_SEARCH_EJB_BINDNAME);
System.out.println("logSearchRemote = " + logSearchRemote);
logSearchRemote.setTest(5);
System.out.println("logSearchRemote.getTest() = " + logSearchRemote.getTest());
System.out.println("logSearchRemote.getTestAgain() = " + logSearchRemote.getTestAgain());
LogSearchRemote logSearchRemote2 = (LogSearchRemote) ctx.lookup(LOG_SEARCH_EJB_BINDNAME);
System.out.println("logSearchRemote2 = " + logSearchRemote2);
System.out.println("logSearchRemote2.getTest() = " + logSearchRemote2.getTest());
System.out.println("logSearchRemote2.getTestAgain() = " + logSearchRemote2.getTestAgain());
this.session = session;
session.setAttribute("LogSearchEJB", logSearchRemote);
System.out.println("logSearchRemote = " + logSearchRemote);
}catch(Exception e){
e.printStackTrace();
}
// if @stateless, throw exception "$Proxy53 cannot be cast to hk.gov.ehr.service.tch.als.admin.logsearch.ejb.LogSearchRemote"
// if @stateful, no error!!
LogSearchRemote logSearchRemote = (LogSearchRemote)session.getAttribute("LogSearchEJB");
//.....
}
}
1) 对于上面的代码,如果 LogSearchRemote 实现 bean 是有状态的,那么
LogSearchRemote logSearchRemote = (LogSearchRemote)session.getAttribute("LogSearchEJB");
没有错误,但是如果 LogSearchRemote implementation bean 是stateless,则抛出异常“$Proxy53 cannot be cast to hk.gov.ehr.service.tch.als.admin.logsearch.ejb.LogSearchRemote”,为什么?
2) 对于有状态会话 bean,我每次都发现
LogSearchRemote logSearchRemote = (LogSearchRemote) ctx.lookup(LOG_SEARCH_EJB_BINDNAME);
返回不同的 logSearchRemote 实现 bean,
但如果是无状态会话 bean,则每次
LogSearchRemote logSearchRemote = (LogSearchRemote) ctx.lookup(LOG_SEARCH_EJB_BINDNAME);
返回相同的bean!
为什么会这样?
我希望无状态会话 bean 不应该保持状态,并且每个查找应该返回一个不同的实现 bean。
@Stateless(name = "AlsAdminLogSearch_1_0", mappedName = "ejb/AlsAdminLogSearch_1_0")
public class LogSearchBean implements LogSearchRemote{
private int test;
@Override
public void setTest(int value){
test = value;
}
@Override
public int getTest(){
return test;
}
@Override
public int getTestAgain(){
return test;
}
//...methods
}
3)当我打电话时
logSearchRemote.setTest(5);
System.out.println("logSearchRemote.getTest() = " + logSearchRemote.getTest());
System.out.println("logSearchRemote.getTestAgain() = "
logSearchRemote.getTestAgain());
对于无状态会话 bean,getTest() 和 getTestAgain() 可以记住之前方法调用中的实例变量“test”!!
为什么会记住?无状态会话 bean 不应该为每个方法调用调用不同的 EJB 实例吗?