Search code examples
restjerseycdibootstrappingweld

Weld (CDI) and Jersey-Server(JAX-RS) Bootstrap in Java SE


I am trying to figure out how to correctly bootstrap Weld (3.0.0) together with Jersey-Server (1.19.3) to establish a Rest Server with Java SE. I am not! talking about a JEE solution. The application server does a good job here. I would like to have it standalone without all the libs I do not need. My problem is that jersey server instantiates all the REST service classes in his own way and not using weld. Therefore @Inject does not work of course. Does IoCInstantiatedComponentProvider help here ?


Solution

  • This is something Hammock provides, but if you want to just leverage the code that's fine. That's the beauty of open source - https://github.com/hammock-project/hammock/tree/master/rest-jersey/src/main/java/ws/ament/hammock/rest/jersey

    Specifically, you'll need to instantiate the JerseyServlet and provide a ServletContextAttribute with the name jersey.config.servlet.internal.resourceConfig_JerseyServlet that points to a ResourceConfig object that either points to your Application object, or has all of the classes registered within it. We use a CDI extension to scrape these classes. I will say I'm using Jersey 2 not Jersey 1, I doubt this will work with Jersey 1 (which was made for CDI 1.0). Note that you need a servlet container still.

    If you want to leverage Hammock, just add these dependencies to your project (I'm using Jetty below, but you can also use embedded tomcat or undertow):

    <dependency>
     <groupId>ws.ament.hammock</groupId>
     <artifactId>rest-jersey</artifactId>
    </dependency>
    <dependency>
     <groupId>ws.ament.hammock</groupId>
     <artifactId>bootstrap-weld3</artifactId>
    </dependency>
    <dependency>
     <groupId>ws.ament.hammock</groupId>
     <artifactId>web-jetty</artifactId>
    </dependency>
    

    And then you just have to provide some annotated rest resources and a beans.xml