mercredi 20 mai 2015

JAVA EE Singleton. One instance?

I'm confused with singletons. I thought that the container creates a singleton only one instance. But the following example made me doubt it. Please explain why different ID displayed.

@Singleton
public class RunBean {
  private int id = new Random().nextInt();

  public void printID() {
    System.out.println("ID = " + id);
  }
  ...
}

@Singleton
public class ParentBean {

  @Inject
  private RunBean runBean;

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

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
  }

}

Aucun commentaire:

Enregistrer un commentaire