title: Java EE 6: How to inject ServletContext into managed bean
body: <p><strong>(Java EE 6 with Glassfish 3.1)</strong></p>
  
  <p>I have a property file that I want to process only once at start up time, so I did this</p>
  
  <pre><code>public class Config implements ServletContextListener{
  
      private static final String CONFIG_FILE_PATH = "C:\\dev\\harry\\core.cfg";
  
      private static final String CONFIG_ATTRIBUTE_NAME = "config";
  
      private long startupTime;
  
      private ConfigRecord config;
  
      @Override
      public void contextInitialized(ServletContextEvent sce) {
          this.startupTime = System.currentTimeMillis() / 1000;
          this.config = new ConfigRecord(CONFIG_FILE_PATH); //Parse the property file
          sce.getServletContext().setAttribute(CONFIG_ATTRIBUTE_NAME, this);
      }
  
      @Override
      public void contextDestroyed(ServletContextEvent sce) {
          //Nothing to do here
      }
  
      public ConfigRecord getConfig() {
          return config;
      }
  
      public long getStartupTime() {
          return startupTime;
      }
  }
  </code></pre>
  
  <p>and in <code>web.xml</code>, i register it as follow</p>
  
  <pre><code>&lt;listener&gt;
      &lt;listener-class&gt;com.wf.docsys.core.servlet.Config&lt;/listener-class&gt;
  &lt;/listener&gt;
  </code></pre>
  
  <p>Now how do I access the <code>ConfigRecord config</code> from the managed bean. I try this</p>
  
  <pre><code>@ManagedBean
  @RequestScoped 
  public class DisplayInbound {
  
      @EJB
      private CoreMainEJBLocal coreMainEJBLocal;
  
      @javax.ws.rs.core.Context
      private ServletContext servletContext;
  
      public void test(){
          Config config = (Config) servletContext.getAttribute("config")
          ConfigRecord configRecord = config.getConfig();
      }
  }
  </code></pre>
  
  <p>I dont think it work. Got <code>NullPointerException</code>. </p>