简体   繁体   English

Lookup返回有状态会话bean的新实例

[英]Lookup returns new instance of Stateful session bean

I am using Java EE 5 , EJB 3.0 , Jboss AS 4.3.2 . 我使用的是Java EE 5EJB 3.0Jboss AS 4.3.2
I have simplest Stateful bean 我有最简单的Stateful

@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);  
   }
}

I do lookup in servlet for this bean 我在servlet中查找这个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");
      // ...
   }
}  

But each time new instance of StateBean is created. 但每次创建StateBean新实例时。
I can call lookup twice but new instance of StateBean is created again 我可以调用两次lookup ,但会再次创建StateBean新实例

   @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
      // ...
   }  

I expect the same instance in the same http-session 我希望在同一个http会话中使用相同的实例

Servlet mapping in web.xml web.xml中的Servlet映射

   <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>

The EJB spec does not say, that multiple lookups will return the same instance of a stateful session bean. EJB规范没有说,多个查找将返回有状态会话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. 相反:服务器甚至需要创建两个不同的实例,以保证每个客户端在服务器上获得自己的实例。

The EJB spec only says that while you're referencing a stateful session bean, it retains its internal state across multiple method invocations: EJB规范只表示当您引用有状态会话bean时,它会在多个方法调用中保留其内部状态:

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

Note that this might NOT be the case when using stateless session beans. 请注意,使用无状态会话Bean时可能不是这种情况。 Here, the two method calls shown above might go to different instances on the server! 这里,上面显示的两个方法调用可能会转到服务器上的不同实例!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM