title: Simple Singleton EJB Example
body: <p>I'm learning EJB's and have written an example program using GlassFish 4 but for some reason it's not working.</p>
  
  <p><strong>index.jsp</strong>:</p>
  
  <pre><code>&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
  &lt;%@ page import="javax.ejb.EJB" %&gt;
  &lt;%@ page import="ejbtest.utility.Utility" %&gt;
  &lt;%@ page import="ejbtest.action.*" %&gt;
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
          &lt;title&gt;EJB Test&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;%
              try {
                  Utility utility = new Utility();
                  out.println("count: " + utility.getCount() + "&lt;br/&gt;&lt;br/&gt;");
                  Trigger1 trigger1 = new Trigger1();
                  out.println("trigger1 count: " + trigger1.getTriggerCount());
              } catch (NullPointerException npe) {
                  out.println("Nullpointer caught");
              }
          %&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>Utility.java</strong>:</p>
  
  <pre><code>package ejbtest.utility;
  
  import javax.ejb.Singleton;
  import javax.ejb.Startup;
  
  @Startup
  @Singleton
  public class Utility {
  
      int count;
  
      public Utility() throws NullPointerException {
          count = 0;
          count++;
      }
  
      public int getCount() {
          return count;
      }
  
      public void setCount(int count) {
          this.count = count;
      }
  }
  </code></pre>
  
  <p><strong>Trigger1.java</strong>:</p>
  
  <pre><code>package ejbtest.action;
  
  import ejbtest.utility.Utility;
  import javax.faces.bean.ApplicationScoped;
  import javax.inject.Inject;
  
  @ApplicationScoped
  public class Trigger1 {
  
      @Inject
      Utility utility;
  
      public Integer getTriggerCount() {
          return utility.getCount();
      }
  
  }
  </code></pre>
  
  <p><strong>Undesired Output</strong>:</p>
  
  <blockquote>
    <p>count: 1</p>
    
    <p>Nullpointer caught</p>
  </blockquote>