Lookup返回有状态会话bean的新实例 [英] Lookup returns new instance of Stateful session bean

查看:180
本文介绍了Lookup返回有状态会话bean的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java EE 5 EJB 3.0 Jboss AS 4.3.2

我最简单有状态 bean

I am using Java EE 5, EJB 3.0, Jboss AS 4.3.2.
I have simplest Stateful bean

@Local
public interface IStateBean 
{
}
@Stateful
public class StateBean implements IStateBean
{  
   private static int number = 0;

   @PostConstruct
   void init()
   {
      number++;
      System.out.println("@PostConstruct: " + number);
   }

   @PreDestroy
   void destroy()
   {
      number--;
      System.out.println("@PreDestroy: " + number);  
   }
}

我在servlet中查找此bean

I do lookup in servlet for this bean

public class MyServlet extends HttpServlet
{  
   @Override
   public void doGet(final HttpServletRequest aRequest, final HttpServletResponse aResponse) throws ServletException, IOException
   {  
      IStateBean bean = new InitialContext().lookup("app-ear/StateBean/local");
      // ...
   }
}  

但每个时间新的 StateBean 实例已创建。

我可以调用 lookup 两次但新实例再次创建 StateBean

But each time new instance of StateBean is created.
I can call lookup twice but new instance of StateBean is created again

   @Override
   public void doGet(final HttpServletRequest aRequest, final HttpServletResponse aResponse) throws ServletException, IOException
   {  
      IStateBean bean1 = new InitialContext().lookup("app-ear/StateBean/local"); 
      IStateBean bean2 = new InitialContext().lookup("app-ear/StateBean/local"); // new instance is created
      // ...
   }  

我希望在同一个http-session中使用相同的实例

web.xml中的Servlet映射

Servlet mapping in web.xml

   <servlet>
      <servlet-name>MyServlet</servlet-name>
      <servlet-class>com.package.MyServlet</servlet-class>
   </servlet>  
   <servlet-mapping>
      <servlet-name>MyServlet</servlet-name>
      <url-pattern>*.html</url-pattern>
   </servlet-mapping>


推荐答案

EJB规范没有说多个查找将会返回有状态会话bean的同一个实例。相反:服务器甚至需要创建两个不同的实例,以保证每个客户端在服务器上获得自己的实例。

The EJB spec does not say, that multiple lookups will return the same instance of a stateful session bean. In opposite: It is even required for the server to create two different instances, to guarantee that every client gets his own instance on the server.

EJB规范只说明了当您引用有状态会话bean时,它会在多个方法调用中保留其内部状态:

The EJB spec only says that while you're referencing a stateful session bean, it retains its internal state across multiple method invocations:

IStateBean bean = new InitialContext().lookup("app-ear/StateBean/local");
bean.myMethod1();
bean.myMethod2(); // affects the same EJB instance on the server

请注意,使用无状态时可能不是这种情况会话bean。在这里,上面显示的两个方法调用可能会转到服务器上的不同实例!

Note that this might NOT be the case when using stateless session beans. Here, the two method calls shown above might go to different instances on the server!

这篇关于Lookup返回有状态会话bean的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆