Jetty Embedded, Jersey 2, Weld

I am using Jetty 9.1 and Jersey 2.5.1. Jersey has native Jetty support, so I start my server as follows:

public static void main(String[] args) { URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build(); ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class); Server server = JettyHttpContainerFactory.createServer(baseUri, config); } 

MyApplication simply calls this.packages(...) to search for my api classes for REST.

However, the REST api class contains an annotated @Inject field that must be entered by WELD. Obviously, WELD does not start (CDI support is not included), and more strange, it seems that HK2 (used by Jersey 2) is trying to inject.

(I have org.glassfish.hk2.api.UnsatisfiedDependencyException when hitting a REST endpoint).

How to configure WELD (preferably programmatically)?

+6
source share
1 answer

I used Weld SE:

 import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; 

And then just

 Weld weld = new Weld(); try { WeldContainer container = weld.initialize(); URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build(); ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class); Server server = JettyHttpContainerFactory.createServer(baseUri, config); server.join(); } catch (Exception e) { e.printStackTrace(); } finally { weld.shutdown(); } 

Note that HK2 will handle REST classes, so I had to write a binder to do the injection work in these classes. This question helped me a lot .

+3
source

All Articles