title: How to enable CDI inject in web service (jaxrs/jersey) on java se running grizzly?
body: <p>How do I allow CDI injection of resources into restful web service resources?  I am running on standard java using weld 2 (cdi), jersey (jaxrs), and grizzly (web server).  Here is my simple web resource:</p>
  
  <pre class="lang-java prettyprint-override"><code>import training.student.StudentRepository;
  import javax.inject.Inject;
  import javax.ws.rs.*;
  
  @Path("student")
  public class StudentWebResource {
    @Inject
    private StudentRepository studentRepository;  
  
    @GET
    @Path("count")
    @Produces(MediaType.TEXT_PLAIN)
    public Integer getCount() {
      return studentRepository.studentCount();
    }
  }
  </code></pre>
  
  <p>And here is how I've got weld starting my simple web server:</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Main {
    public static void main(String[] args) throws Exception {
      startCdiApplication();
    }
  
    public static void startCdiApplication() throws Exception {
      Weld weld = new Weld();
      try {
        WeldContainer container = weld.initialize();
        Application application = container.instance().select(WebServer.class).get();
        application.run();
      } 
      finally {
        weld.shutdown();
      }
    }
  }
  </code></pre>
  
  <p>And the code that I suspect will need to be modified to inform jersey to use weld for CDI inject resolution:</p>
  
  <pre><code>...
  import org.glassfish.grizzly.http.server.HttpServer;
  import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
  import org.glassfish.jersey.jackson.JacksonFeature;
  import org.glassfish.jersey.server.ResourceConfig;
  
  public class WebServer implements Application {
  
    /*
     * startup the grizzly http server to make available the restful web services
     */
    private void startWebServer() throws IOException, InterruptedException {
      final ResourceConfig resourceConfig = new ResourceConfig().packages("training.webservice").register(new JacksonFeature());
      final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseUri(), resourceConfig);
      server.start();
      Thread.currentThread().join();
    }
  
    ...
  
    @Override
    public void run() throws IOException, InterruptedException {
      startWebServer();
    }
  }
  </code></pre>