我正在使用Java EE 5
, EJB 3.0
, Jboss AS 4.3.2
.
我有最简单的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);
}
}
我在 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");
// ...
}
}
但是每次StateBean
创建新实例时。
我可以调用两次,但会再次创建 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
// ...
}
我希望在同一个 http-session 中有同一个实例
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>