Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetty Embedded, Jersey 2, Weld

I'm using Jetty 9.1 and Jersey 2.5.1. Jersey has built-in support for Jetty, so I start my server like that:

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 lookup my REST api classes.

However, the REST api class contains a @Inject annotated field, which should be injected by WELD. Obviously WELD is not started (CDI support not enabled), and weirder, it looks like HK2 (used by Jersey 2) is trying to perform the injection.

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

How do I setup correctly WELD (preferably programmatically)?

like image 881
coffee_machine Avatar asked Jan 08 '14 15:01

coffee_machine


1 Answers

I used Weld SE:

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

And then simply

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 make the injection work in those classes. This question helped me a lot.

like image 77
coffee_machine Avatar answered Oct 15 '22 06:10

coffee_machine