How to set an AbstractBinder in Jersey

5.4k views Asked by At

I'm trying to implement my HK2 binding in Jersey, in a servlet / tomcat context.

I do, in a servlet which extends org.glassfish.jersey.servlet.ServletContainer :

  @Override
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
    // BinderInjection extends org.glassfish.hk2.utilities.binding.AbstractBinder
    getConfiguration().register(new BinderInjection()); 
  }

... but I get :

java.lang.IllegalStateException: The resource configuration is not modifiable in this context.
    at org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:270)
    at org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:218)
    at org.glassfish.jersey.server.ResourceConfig.register(ResourceConfig.java:448)
    at A_Servlet.init(RestServlet.java:45)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1190)

So how can I do my own HK2 binding ?

Why this question ? (edit)

It's for EntityManager and JPA in Jersey.

With Netbeans, if I generate an AbstractFacade it put

  @PersistenceContext(unitName = "myunit")
  private EntityManager em;

... and :

  @Override
  protected EntityManager getEntityManager()
  {
    return em;
  }

But, when I call the service, em is null. So I suppose it's @PersistenceContext which doesn't work ?

If I use the solution Tutorial: Put JPA in your Web App (tomcat, EclipseLink) and provide Rest JSON output all work like a charm, but I don't like use static variable private static EntityManagerFactory emf; for entity manager.

Thanks.

1

There are 1 answers

0
Rohit Gupta On

Below is an example where I am binding a Spring injected jersey resource to the Jetty Webserver. ResourceConfig utility is provided by Jersey. Hope this example helps. p.s. -- restService is a Spring injected dependency

    ResourceConfig config = new ResourceConfig(CustomRestService.class);
                config.register(new AbstractBinder() {

                    @Override
                    protected void configure() {
                        bind(restService).to(CustomRestService.class);
                    }
                });

                restService.start();
                ServletHolder apiServlet = new ServletHolder(new ServletContainer(config));
                ServletHolder apiServlet = new ServletHolder(new HttpServletDispatcher());
                servletContainer.addServlet(apiServlet, "/api/v1*//*");