Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

No Format
public class SingletonFactory implements ServletContextListener {
  public static final String MY_CLASS = "...";

  private static MyClass mcInstance = new MyClass();

  /**
   * @see ServletContextListener#contextInitialized(ServletContextEvent)
   */
  public void contextInitialized(ServletContextEvent event) {
    ServletContext ctx = event.getServletContext();
    ctx.setAttribute(MY_CLASS, new mcInstanceMyClass());
  }

  /**
   * @see ServletContextListener#contextDestroyed(ServletContextEvent)
   */
  public void contextDestroyed(ServletContextEvent event) {
    mcInstance =ctx.setAttribute(MY_CLASS, null);
  }

  /**
   * Optional method for getting the MyClass singleton instance.
   */
  public static MyClass getMyClassInstance(ServletContext ctx) {
    return mcInstance(MyClass)ctx.getAttribute(MY_CLASS);
  }
}
  • Register the listener in the web.xml descriptor
  • Replace the calls to MyClass.getInstance() by:
No Format
  MyClass instance = (MyClass)ctx.getAttribute(SingletonFactory.MY_CLASS);

  /* or */
, if implemented:
  MyClass instance = SingletonFactory.getMyClassInstance(ctx);
  */