title: Injecting an EJB into a dynamic mapped servlet
body: <p>I have a filter where I am dinamically mapping servlet classes:</p>
  
  <pre><code>    @Override
      public void init( FilterConfig filterConfig ) throws ServletException {
          servletContext = filterConfig.getServletContext();
  
          File directory = getConventionDirectory();
          FileSystemInspector fileInspector = new FileSystemInspector();
          Set&lt;ActionInfoData&gt; actions = fileInspector.getActions( directory );
  
          for ( ActionInfoData action : actions ) {
              servletContext
                  .addServlet( action.getServletName(), action.getClassName() )
                  .addMapping( action.getServletMapping() );
          }
  
      }
  </code></pre>
  
  <p>Then when I access a given mapping the EJB is not injected.</p>
  
  <pre><code>    @EJB
      private I18nManager i18nManager;
  
      @Override
      protected void doGet( HttpServletRequest request, HttpServletResponse response )
      throws ServletException, IOException {
          I18nManager i18n = i18nManager; //null
      }
  </code></pre>
  
  <p>If I manually create a mapping in the web.xml <strong>the given EJB is working</strong> in that servlet.
  It makes me wonder if the fact I am registering the servlets at runtime the container does not consider those servlets as managed.</p>
  
  <p>If that is the case what is the proper way to inject the EJBs into my servlets without changing the way they are dinamically registered via filter?</p>
  
  <p>Is via JNDI the only way to inject my EJBs?</p>
  
  <p>EDIT 1:
  I have tried to implement a <code>ServletContextListener</code> class as suggested by "Will" using the following code in the <code>web.xml</code>:</p>
  
  <pre><code>&lt;listener&gt;
          &lt;listener-class&gt;com.megafone.web.filter.convention.InitServlet&lt;/listener-class&gt;
      &lt;/listener&gt;
  </code></pre>
  
  <p>And the relevant part of the implementation:</p>
  
  <pre><code>...
  
  @Override
      public void contextInitialized( ServletContextEvent sce ) {
          ServletContext servletContext = sce.getServletContext();
  
          FileSystemInspector fileInspector = new FileSystemInspector();
          Set&lt;ActionInfoData&gt; actions = fileInspector.getActions( getConventionDirectory() );
  
          for ( ActionInfoData action : actions ) {
              servletContext
                  .addServlet( action.getServletName(), action.getClassName() )
                  .addMapping( action.getServletMapping() );
          }
      }
  
  ...
  </code></pre>
  
  <p>Unfortunately it does not make the container inject the EJBs and the null pointer remains. I am currently making a custom type safe JNDI lookup to the service. Obviously this is far more expensive than using the proper injection (correct me if I am wrong, have done no experiments regarding performance yet).</p>
  
  <p>Using:<br>
  Java EE 6<br>
  JBoss AS 7.1</p>