@Singleton @Inject-ed在@WebServlet中似乎创建了多个实例

时间:2015-05-20 20:08:40

标签: java-ee singleton ejb cdi

我是以下@Singleton public class RunBean { private int id = new Random().nextInt(); public void printID() { System.out.println("ID = " + id); } } EJB:

@Singleton
public class ParentBean {

  @Inject
  private RunBean runBean;

  public void start() {
    runBean.printID();
  }

}
@Inject

public class Servlet extends HttpServlet { @Inject private RunBean runBean; @Inject private ParentBean parentBean; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { runBean.printID(); // out: ID = 69743 parentBean.start(); // out: ID = 193 } } - 将它们放在下面的网络servlet中:

1.txt

我希望看到相同的ID被打印出来。他们为什么不同?

1 个答案:

答案 0 :(得分:1)

您应该只在JavaEE 7或更新的服务器上@Inject EJB(例如@Singleton bean)。

在Java EE6环境中,您必须使用@EJB